JNI on Android: how to get a string from Java code?

I read a lot of examples to get a java string in C / C ++ code, but it seems like I'm missing something. This simple code does not work.

In ActivityTest (Android Java code), I:

public static native void nativeInit(String stringfromjava);

In TestActivity, I have:

ActivityTest.nativeInit("test");

and in my test-jni.c:

JNIEXPORT void JNICALL  Java_com_test_jni_ActivityTest_nativeInit(JNIEnv* env, jclass cls, jobject obj, jstring stringfromjava){

__android_log_print(ANDROID_LOG_INFO, "TESTJNI","Native Init started");

const char* w_buf = (*env)->GetStringUTFChars(env, stringfromjava, 0);

if(w_buf == NULL) {
    __android_log_print(ANDROID_LOG_INFO, "TESTJNI","file path recv nothing");
}

else {
        __android_log_print(ANDROID_LOG_INFO, "TESTJNI","String: %s", w_buf);
}

(*env)->ReleaseStringUTFChars(env, stringfromjava, w_buf);

}

But in my logcat, I only get:

I/TESTJNI (18921): Native Init started
I/TESTJNI (18921): String: 

Where am I mistaken ...?

Fixed Thanks to Mario, removing the "jobject obj" from the signature fixed my problem!

+5
source share
1 answer

Wrote only one short test (similar to your program), but my function had a slightly different signature (it may depend on the SDK / NDK / JDK version, took it from some tutorial code that I found):

extern "C" void Java_com_whatever_Activity_method(JNIEnv* env, jobject jthis, jstring param);

Obviously, you won't need extern "C"it unless you write C ++.

Java:

native void method(String param);

Edit:

( , 100% , ):

const char *cparam = env->GetStringUTFChars(param, 0);
// .. do something with it
env->ReleaseStringUTFChars(param, cparam);

, - . , , .

+4

All Articles