![]() ![]() ![]() ![]() |
Implementing Native Methods |
The Java development environment provides several functions useful for manipulating Java strings in a native method. These functions are defined injavaString.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 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.There are two other string functions defined 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()
. It produces a C string from a Java String. You use it like this:result = makeCString(aJavaString);makeCString()
returns achar *
that points to a null-terminated C string that contains 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()
but the caller is responsible for freeing the returned pointer.
![]() ![]() ![]() ![]() |
Implementing Native Methods |