Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing string from Java into JNI

I want to pass a string into the JNI I am writing which have to be assigned to a const char*. The below mentioned is how I have done it:

JNI...(...,jstring jstr...){

const char* str = env->GetStringUTFChars(jstr,0);
env->ReleaseStringUTFChars(str,jstr,0);

}

But if i printf the const char* str after assigning to the jstring what I see is different as compared to when I assigned the str value directly in the JNI and printf from there.

Is this the correct way to do? Or is there any other way to assign a string from java to const char* in JNI ?

like image 748
perumal316 Avatar asked Nov 22 '10 15:11

perumal316


3 Answers

java code

public static native double myMethod( String path);  

C Code

JNIEXPORT jdouble JNICALL Java_your_package_structure_className_myMethod
(JNIEnv * env, jobject jobj, jstring pathObj) {
     char * path;

    path = (*env)->GetStringUTFChars( env, pathObj, NULL ) ;
  • Updated link
like image 160
jmj Avatar answered Oct 18 '22 08:10

jmj


All you do is correct. There is other way but to obtain wchar_t instead of char:

const wchar_t * utf16 = (wchar_t *)env->GetStringChars(bytes, NULL);
size_t length = (size_t)env->GetStringLength(bytes);        
...
env->ReleaseStringChars(bytes, (jchar *)utf16);
like image 39
Vladimir Ivanov Avatar answered Oct 18 '22 07:10

Vladimir Ivanov


JNIEXPORT jstring JNICALL Java_Hello_sayHi(JNIEnv *env, jobject obj, jstring string) {
     const char *str = env->GetStringUTFChars(string, 0);
     printf("%s", str);
}
like image 3
prem kumar Avatar answered Oct 18 '22 06:10

prem kumar