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 defined in javaString.h.

The InputFile_open() function 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));
buf 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.

There are two other string functions defined 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(). It produces a C string from a Java String. You use it like this:

result = makeCString(aJavaString);
makeCString() returns a char * that points to a null-terminated C string that contains 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() but the caller is responsible for freeing the returned pointer.


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