2

I'm trying to return a string from native. For that I'm using the following code.

Native:

#include <string.h>
#include <jni.h>

jstring Java_com_test_Demo_getString(JNIEnv *env, jobject javaThis) {
    return (*env)->NewStringUTF(env, "hello");
}

Java:

private native String getString(); //in com.test.Demo

After this I'm generating .so files using ndk-build and including them in jniLibs.

However, the string returned is null. Any ideas on what is wrong ?

Michael
  • 57,169
  • 9
  • 80
  • 125
Gaurav Arora
  • 17,124
  • 5
  • 33
  • 44
  • Nope. Just returns null value. Most likely, it can't link native method. – Gaurav Arora Oct 04 '15 at 03:52
  • 1
    try JNIEXPORT jstring JNICALL Java_com_test_Demo_getString(JNIEnv *env, jobject javaThis) { return (*env)->NewStringUTF(env, "hello"); } – samgak Oct 04 '15 at 06:59
  • @samgak I also found this on some tutorial yesterday. Luckily, this works but I don't know why ! Can you explain this ? – Gaurav Arora Oct 05 '15 at 11:20
  • 1
    JNIEXPORT is used to include the function in the dynamic table of the .so file so that it can be linked at runtime. JNICALL is used to specify the calling convention (it actually does nothing on Android because the default one is correct). See [this answer](http://stackoverflow.com/questions/19422660/when-to-use-jniexport-and-jnicall-in-android-ndk) – samgak Oct 05 '15 at 12:21
  • What is wrong is almost certainly that you aren't executing this code. – user207421 May 20 '17 at 00:54

0 Answers0