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:

1
2
3
4
5
6
7
8
9
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:

1
2
3
4
JNIEXPORT jstring JNICALLJava_MyJavaClass_getName(JNIEnv *env, jobject obj)
{
	return (*env)->NewStringUTF(env, “Electrofriends.com);
}

Leave a Reply