JNI 動態註冊
摘要:
public class MainActivity extends AppCompatActivity {
// 載入so
static {
System.loadLibrary("native-lib");
}
@Overr...
public class MainActivity extends AppCompatActivity { // 載入so static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = findViewById(R.id.sample_text); tv.setText(getString()); } /** * 定義native方法 */ public native String getString(); } 複製程式碼
#include <jni.h> #include <string> /** * extern "C" :主要作用就是為了能夠正確實現C++程式碼呼叫其他C語言程式碼 * JNIEXPORT,JNICALL :告訴虛擬機器,這是jni函式 */ extern "C" JNIEXPORT jstring JNICALL native_getString(JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); } /** * 對應java類的全路徑名,.用/代替 */ const char *classPathName = "com/chenpeng/registernativemethoddemo/MainActivity"; /** * JNINativeMethod 結構體的陣列 * 結構體引數1:對應java類總的native方法 * 結構體引數2:對應java類總的native方法的描述資訊,用javap -s xxxx.class 檢視 * 結構體引數3:c/c++ 種對應的方法名 */ JNINativeMethod method[] = {{"getString", "()Ljava/lang/String;", (void *) native_getString}}; /** * 該函式定義在jni.h標頭檔案中,System.loadLibrary()時會呼叫JNI_OnLoad()函式 */ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { //定義 JNIEnv 指標 JNIEnv *env = NULL; //獲取 JNIEnv vm->GetEnv((void **) &env, JNI_VERSION_1_6); //獲取對應的java類 jclass clazz = env->FindClass(classPathName); //註冊native方法 env->RegisterNatives(clazz, method, 1); //返回Jni 的版本 return JNI_VERSION_1_6; } 複製程式碼