Friday 15 May 2015

Using Java Strings from Native Methods in Java

 Because there is an "impedance mismatch" between Java strings and C strings, there are several convenience functions that allow C code to use the Java strings. Java strings offer several advantages over C strings, including reference counting, automatic memory management, and Unicode support. On the other hand, no C runtime library function or API function will expect a Java string. The utility functions provide a bridge between Java and C strings.
These functions are defined in javaString.h, which will be included automatically if you include StubPreamble.h:
  • The following function will print a Java string on stdout: 
    void javaStringPrint(Hjava_lang_String *)
  • The following function returns the length of the Java string, in characters:
    int javaStringLength(Hjava_lang_String *)
  • The following function will construct a new Java string from a given C string. The second argument indicates the length of the buffer passed in the first argument:
    Hjava_lang_String *makeJavaString(char *, int)
  • The following interesting function allocates some temporary memory for a C string initialized from the given Java string. Once all references to this storage are eliminated, the memory is automatically deallocated. In other words, as long as you keep this pointer in a variable, the memory is valid:
    char *makeCString(Hjava_lang_String *)
  • The following function uses "malloc" to allocate some memory for a C string initialized from the given Java string: 
    char *mallocCString(Hjava_lang_String *)
  • The following function will convert the characters of the given Java string into a unicode string. It assumes that the buffer passed in as the second argument already exists. The third argument specifies the buffer length. The function returns the unicode string's address:
    unicode *javaString2unicode(Hjava_lang_String *, unicode*, int)
  • The following function will convert the characters of the given Java string into a C string. It assumes that the buffer passed in as the second argument already exists. The third argument specifies the buffer length. The function returns the C string's address:
    char *javaString2Cstring(Hjava_lang_String *, char *, int)

No comments:

Post a Comment