Detailed explanation of JNIEnv parameters for ndk development and ndkjnienv Parameters
Even if our Java-layer functions have no parameters, the native method still comes with two parameters. The first parameter is JNIEnv.
As follows:
Native method:
public native String stringFromC(); public native String stringFromCpp();
Native method:
jstring Java_com_example_jni_MainActivity_stringFromC(JNIEnv* env,jobject thiz){ return (*env)->NewStringUTF(env,"I am from C");}extern "C" jstring Java_com_example_jni_MainActivity_stringFromCpp(JNIEnv* env,jobject thiz){ return env->NewStringUTF("I am from C++");}
JNIEnv is an interface pointer to the available JNI function table. native code uses the functions provided by the JNIEnv interface pointer to use the functions of virtual machines. JNIEnv is a pointer to the thread-local data, and the thread-local data contains a pointer to the thread table. Functions that implement native methods use JNIEnv interface pointers as their first parameters.
The native code is C and the native code is C ++. The syntax for calling JNI functions is different.In the C code, JNIEnv is a pointer to the JNINativeInterface structure. to access any JNI function, the pointer must be unreferenced first. Because the JNI function in C code does not understand the current JNI environment, the JNIEnv instance should be passed to every JNI function caller as the first parameter.
The correct statement is as follows:
jstring Java_com_example_jni_MainActivity_stringFromC(JNIEnv* env,jobject thiz){ return (*env)->NewStringUTF(env,"I am from C");}
However,In C ++ code, JNIEnv is actually a C ++ class instance. JNI functions exist as member functions because the JNI method has accessed the current JNI environment, therefore, JNI method calls do not require JNIEnv instances as parameters. In C ++, the code for completing the same function should be as follows:
extern "C" jstring Java_com_example_jni_MainActivity_stringFromCpp(JNIEnv* env,jobject thiz){ return env->NewStringUTF("I am from C++");}
Download the source code of this project
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger. I am very grateful if you have any mistakes.