The method is declared in java

public native String stringFromJNI(byte[] b); 

And on c ++ function is declared

 Java_theflipsiderebirth_testclintgame_1write_1in_1androidstudio_MainActivity_stringFromJNI(JNIEnv* env, object obj, jbyte b[]){...} 

However, the address in variable b is garbage. Why?

  • Probably, you first need to allocate space in the unmanaged memory, copy your array there and pass the function a pointer to this memory. Since the memory allocated in the heap is dynamic and the pointers to the objects may change in the process of heap compression. - Artyom Okonechnikov

1 answer 1

Because the function declaration is incorrect. The javah utility generates this definition.

 JNIEXPORT jstring JNICALL Java_MainActivity_stringFromJNI (JNIEnv *, jobject, jbyteArray); 

Please note that jbyteArray is not byte[] , it is a type of reference to an array of bytes.

 JNIEXPORT jstring JNICALL Java_MainActivity_stringFromJNI(JNIEnv* env, jobject obj, jbyteArray b) { jsize size = env->GetArrayLength(b); jbyte* buffer = env->GetByteArrayElements(NULL); ... env->ReleaseByteArrayElements(b, buffer, JNI_ABORT); }