JNI converting jstring to char *

Prasham picture Prasham · Nov 15, 2010 · Viewed 117k times · Source

I have passed a URL string from Java to C code as jstring data type through the use of JNI. And my library method needs a char * as url.

How can I convert jstring in char * ?

P.S.: Is there any advantage of using jcharArray in C? (i.e. Passing char [] instead of string in native method)

Answer

Jason Rogers picture Jason Rogers · Nov 15, 2010

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}