Implementing Native Methods |
The Java development environment provides several functions useful for manipulating Java strings in a native method. These functions are declared injavaString.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:Thechar buf[MAXPATHLEN]; javaString2CString(unhand(this)->path, buf, sizeof(buf));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 variablepath
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 (achar *
) from a Java String. The second,makeJavaString()
, creates a Java String object from a C string (achar *
).The
makeCString()
function is similar tojavaString2CString()
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 achar *
value that points to a null-terminated C string that containing the data fromaJavaString
.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
ThejavaString.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.
Implementing Native Methods |