Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Implementing Native Methods


Working with Strings

The Java development environment provides several functions useful for manipulating Java strings in a native method. These functions are declared in javaString.h.

The InputFile_open() function in the Character Replace example uses one of these functions, javaString2CString(), to fill up a C character array with data from a Java String object. Here's the relevant code:

char buf[MAXPATHLEN];
javaString2CString(unhand(this)->path, buf, sizeof(buf));
The buf argument is a C character array. This array will be filled with characters from a Java String object.

The first argument to javaString2CString() is the Java String to copy into the C character array. unhand(this)->path gets the instance variable path from the InputFile object. path is a Java String object. The second argument is the character array to copy the characters into, and the third argument is the length of the character array.

Two other string functions are declared in javaString.h that you are likely to use frequently. The first, makeCString(), creates a C string (a char *) from a Java String. The second, makeJavaString(), creates a Java String object from a C string (a char *).

The makeCString() function is similar to javaString2CString() except that it allocates memory for the C string. It produces a C string from a Java String. You use it like this:

result = makeCString(aJavaString);
makeCString() returns a char * value that points to a null-terminated C string that containing the data from aJavaString.

The makeJavaString() function creates a new Java String object from a C string. makeJavaString() is often used when returning a String value from a native method:

char *result;
    . . .
return makeJavaString(result, strlen(result));

Other Useful String Functions

The javaString.h header file includes several other useful string manipulation functions:
javaStringPrint()
Prints a Java String from a native method.
javaStringLength
Returns the length of a Java String.
allocCString
Similar to makeCString(), except that it allocates memory for the C string.


Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Implementing Native Methods