課程
/移動開發(fā)
/Android
/Android CMake以及NDK實踐基礎
怎么創(chuàng)建一個動態(tài)注冊項目?
2020-04-09
源自:Android CMake以及NDK實踐基礎 2-2
正在回答
JNIDynamicLoad.java public?class?JNIDynamicLoad?{ ????static?{ ????????System.loadLibrary("dynamic-lib"); ????} ????public?native?int?getRandomNum(); ????public?native?String?getNativeString(); }
jni_dynamic_load.cpp
// //?Created?by?admin?on?2020-04-27. // #include?<jni.h> #include?<cassert> #include?<cstdlib> #include?<iostream> using?namespace?std; jint?get_random_num(JNIEnv?*env)?{ ????return?rand(); } jstring?get_native_string(JNIEnv?*env)?{ ????return?env->NewStringUTF("jni動態(tài)加載的字符串,嘿嘿嘿"); } /** ?*?需要注冊的函數(shù)列表,放在JNINativeMethod類型的數(shù)組中,以后如果需要增加函數(shù),只需在這里添加就行了 ?*?參數(shù): ?*?1、java代碼中用native關鍵字聲明的函數(shù)名字符串 ?*?2、簽名(傳進來參數(shù)類型和返回值類型的說明) ?*?3、C/C++中對應函數(shù)的函數(shù)名(地址) ?*/ static?JNINativeMethod?getMethods[]?=?{ ????????{"getRandomNum",????"()I",??????????????????(void?*)?get_random_num}, ????????{"getNativeString",?"()Ljava/lang/String;",?(void?*)?get_native_string} }; /** ?*?此函數(shù)通過調用JNI中?RegisterNatives?方法來注冊我們的函數(shù) ?*?@param?env ?*?@param?className ?*?@param?methods ?*?@param?nMethods ?*?@return ?*/ static?int?registerNativeMethods(JNIEnv?*env,?const?char?*className,?const?JNINativeMethod?*methods, ?????????????????????????????????jint?nMethods)?{ ????jclass?clazz; ????//找到聲明native方法的類 ????clazz?=?env->FindClass(className); ????if?(clazz?==?NULL)?{ ????????return?JNI_FALSE; ????} ????if?(env->RegisterNatives(clazz,?methods,?nMethods)?<?0)?{ ????????return?JNI_FALSE; ????} ????return?JNI_TRUE; } static?int?registerNatives(JNIEnv?*env)?{ ????const?char?*className?=?"com/example/jnidemo3/load/JNIDynamicLoad"; ????return?registerNativeMethods(env,?className,?getMethods, ?????????????????????????????????sizeof(getMethods)?/?sizeof(getMethods[0])); } JNIEXPORT?jint?JNICALL?JNI_OnLoad(JavaVM?*vm,?void?*reserved)?{ ????JNIEnv?*env?=?NULL; ????//判斷虛擬機狀態(tài)是否有問題 ????if?(vm->GetEnv((void?**)?&env,?JNI_VERSION_1_6)?!=?JNI_OK)?{ ????????return?-1; ????} ????assert(env?!=?NULL); ????if?(!registerNatives(env))?{ ????????return?-1; ????} ????return?JNI_VERSION_1_6; }
CMakeList.txt
add_library( ????????dynamic-lib ????????SHARED ????????jni/jni_dynamic_load.cpp ) target_link_libraries( ????????dynamic-lib ????????${log-lib})
如果還有疑惑,可以看我練習的代碼https://github.com/shuiyouwen/JniDemo3
舉報
Android底層開發(fā)入門必備,CMake動態(tài)庫編譯和使用,NDK的各種開發(fā)技巧。
1 回答請問windows下的jni編譯為dll,如何動態(tài)注冊??
1 回答請問windows平臺下的jni編譯為dll,如何動態(tài)注冊??
1 回答請問在項目中jvm.h等怎么寫的
1 回答JNI項目
2 回答*threadCallback 這個是怎么調用的呢?
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動學習伙伴
掃描二維碼關注慕課網(wǎng)微信公眾號
2020-04-29
jni_dynamic_load.cpp
CMakeList.txt
如果還有疑惑,可以看我練習的代碼
https://github.com/shuiyouwen/JniDemo3