標籤:內容 自動 參數 改名 源檔案 main 靜態 generate mic
這篇說靜態註冊,所謂靜態註冊,就是native的方法是直接通過方法名的規定格式和Java端的聲明處代碼對應起來的,對於規則如下:
JNIEXPORT <傳回值> JNICALL Java_<包路徑(.換成_)>_<類名>_<方法名>(JNIEnv *, jobject<,方法參數>)
假設在HelloJni中聲明了方法staticLoad(), 如下所示:
package com.example.zhanghaiqiang.hellojni;public class HelloJni { static{ System.loadLibrary("main"); } public native void staticLoad();}
則其對應的native方法名為
JNIEXPORT void JNICALL Java_com_example_zhanghaiqiang_hellojni_AndroidJni_dynamicLog (JNIEnv *, jobject)
當然,這個規則並不需要死記,jdk中的javah自動就幫我們做這個事了,cd到java目錄下,執行 javah <包路徑>.<類名> ,就會在目前的目錄下產生對應的natvie類 的標頭檔,比如上面的HelloJni,執行javah後得到的com_example_zhanghaiqiang_hellojni_HelloJni.h檔案內容就會像這樣:
/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class com_example_zhanghaiqiang_hellojni_HelloJni */#ifndef _Included_com_example_zhanghaiqiang_hellojni_HelloJni#define _Included_com_example_zhanghaiqiang_hellojni_HelloJni#ifdef __cplusplusextern "C" {#endif/* * Class: com_example_zhanghaiqiang_hellojni_HelloJni * Method: staticLog * Signature: ()V */JNIEXPORT void JNICALL Java_com_example_zhanghaiqiang_hellojni_HelloJni_staticLog (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif
隨後,把這個檔案拷到預設的jni目錄下,copy一份並改名為.c或者.cpp源檔案(當然你也可以直接把這個.h檔案改成源檔案),然後就可以開始寫native的方法實現了。
Android JNI之靜態註冊