5

I read a lot of examples to retrieve a java string in C/C++ code, but it seems that I miss something. this simple code doesn't work..

In ActivityTest (android java code) I've:

public static native void nativeInit(String stringfromjava);

In TestActivity I've:

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 get only:

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

Where I'm wrong...?

FIXED Thanks to Mario, removing "jobject obj" from the signature fixed my issue!

2
  • If Mario's answer fixed the problem for you, you should mark his answer as accepted (click the tick next to his answer). Commented Feb 1, 2012 at 2:30
  • Did you add a static block in Java like this: static { nativeInit(); } Commented Jun 3, 2016 at 15:27

1 Answer 1

4

Only wrote one short test so far (similar to your program), but my function had a bit different signature (might depend on SDK/NDK/JDK version? took it from some tutorial code I found):

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

Obviously you won't need extern "C" if you're not writing C++.

The Java signature would be:

native void method(String param);

Edit:

To obtain the string (not sure if this is 100% correct, but it works):

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

Open to suggestions in case there's something wrong in there. It works fine, but might still be some issue, so feel free to comment.

Sign up to request clarification or add additional context in comments.

2 Comments

that's the same thing the OP did.
@ethan: It's not. I'm skipping the jclass in the parameter list as well as JNIEnv in the string functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.