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 ?

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 ) ;

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);

Actually, solution is simple: the last parameter of "GetStringUTFChars" is JNI_TRUE to send a copy. Since you are passing JNI_FALSE (0) and calling "ReleaseStringUTFChars", you are destroying the reference. What you see after "releasing" are random bytes from elsewhere in your application memory.

Calling "GetStringUTFChars" with JNI_TRUE or removing the "ReleaseStringUTFChars" call will solve your problem.

EDIT: Sorry about graveyard digging.


As #Jigar explained:

JNIEXPORT jdouble JNICALL Java_your_package_structure_className_myMethod
(JNIEnv * env, jobject jobj, jstring jstr) {


    const char *path = (*env)->GetStringUTFChars( env, jstr , NULL ) ;

in order to get a jstring from java, one should write c++ method as below

C++ code:

const char *path = env->GetStringUTFChars(jstr , NULL ) ;

UPDATE: As mentioned in comments, there was a mistake in the code. It's now fixed.


JNIEXPORT jstring JNICALL Java_Hello_sayHi(JNIEnv *env, jobject obj, jstring string) {
     const char *str = env->GetStringUTFChars(string, 0);
     printf("%s", str);
}

Need Your Help

simultaneous read-write a file in C#

c# filestream streamreader streamwriter

I have a file containing data that I'd like to monitor changes to, as well as add changes of my own. Think like "Tail -f foo.txt".

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

php json xmlhttprequest

file_get_contents("php://input") or $HTTP_RAW_POST_DATA - which one is better to get the body of JSON request?