1. 程式人生 > 實用技巧 >JNI開發:靜態註冊和動態註冊

JNI開發:靜態註冊和動態註冊

1. 靜態註冊

jni開發中預設註冊方式為靜態註冊,具體如下:

// MainActivity.java
public
class MainActivity extends AppCompatActivity { 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(stringFromJNI()); } public native String stringFromJNI(); }
// native-lib.cpp
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myndkproject_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "
Hello from C++ 靜態註冊"; return env->NewStringUTF(hello.c_str()); }

在java中通過native stringFromJNI()呼叫Java_com_example_myndkproject_MainActivity_stringFromJNI,達到使用C++程式碼開發核心內容的目的。

2. 動態註冊

// MainActivity.java
public class MainActivity extends AppCompatActivity {
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(stringFromJNI());
Log.i("MainActivity",add_java(1,2)+"");
}
public native String stringFromJNI();
public native int add_java(int a,int b);

}
// native-lib.cpp
jstring stringFromJNI(JNIEnv *env, jobject thiz){
    std::string hello = "Hello from C++ 動態註冊";
    return env->NewStringUTF(hello.c_str());
}

jint add_jni(JNIEnv *env,jobject thiz,jint a, jint b )
{
    return a+b;
}

static const JNINativeMethod gMethods[] = {
        {"stringFromJNI", "()Ljava/lang/String;", (jstring*)stringFromJNI},
        {"add_java","(II)I",(jint*)add_jni},

};

JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){

    __android_log_print(ANDROID_LOG_INFO, "native", "Jni_OnLoad");
    JNIEnv* env = NULL;
    if(vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) //從JavaVM獲取JNIEnv,一般使用1.4的版本
        return -1;
    jclass clazz = env->FindClass("com/example/myndkproject/MainActivity");
    if (!clazz){
        __android_log_print(ANDROID_LOG_INFO, "native", "cannot get class: com/example/myndkproject/MainActivity");
        return -1;
    }
    if(env->RegisterNatives(clazz, gMethods, sizeof(gMethods)/sizeof(gMethods[0])))
    {
        __android_log_print(ANDROID_LOG_INFO, "native", "register native method failed!\n");
        return -1;
    }
    return JNI_VERSION_1_4;
}