How to convert a jstring to a C-style string or vice versa!

The jstring type represents strings in the Java virtual machine, and is different from the regular C string type (a pointer to characters, char *). So we cannot use a jstring as a normal C string. We must use the appropriate JNI functions to convert jstring objects to C/C++ strings. The JNI supports conversion both to and from Unicode and UTF-8 strings. Unicode strings represent characters as 16-bit values, whereas UTF-8 strings use an encoding scheme that is upward compatible with 7-bit ASCII strings. UTF-8 strings act like NULL-terminated C strings.
jstring, which requires a subroutine call to in order to convert a Java Unicode string (2 bytes) to a C-style char* string (1 byte UTF-8 format).
To convert a jstring to a C-style string, you might write code like the following:

JNIEXPORT void JNICALLJava_MyJavaClass_printName(JNIEnv *env, jobject obj,
jstring name)
{
const char *str= (*env)->GetStringUTFChars(env,name,0);
printf(“%s”, str);
//need to release this string when done with it in order to
//avoid memory leak
(*env)->ReleaseStringUTFChars(env, name, str);
}

To convert a C-style string to jstring , you can use the (*env)->NewStringUTF() function to create a new jstring from a C-style string. For example, a C function that needs to return a Java string could contain the following code:
JNIEXPORT jstring JNICALLJava_MyJavaClass_getName(JNIEnv *env, jobject obj)
{
return (*env)->NewStringUTF(env, “betaengineers.net”);
}
Share on Google Plus

About sNova

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment

Thanks for your Valuable comment