NDK(15)在ndk代码中注册和注销native函数

 

  转自:  http://www.cnblogs.com/canphp/archive/2012/11/13/2768937.html

 

C和C++注册native函数的方式大致上相同,下面给出具体的代码。

 

 1 /* JNINativeMethod数组的定义在C和C++中都一样*/  
 2 static JNINativeMethod gMethods[] = {  
 3     {  
 4         "jobjectProcess",  
 5         "(Lcom/example/hellojni/HelloJni$Student;Ljava/lang/Integer;)V",  
 6         (void*)jobjectProcess  
 7     }  
 8     /*被省略掉的代码*/  
 9 };  
10   
11 jint JNI_OnLoad(JavaVM* vm,void* reserved)  
12 {  
13     JNIEnv* env = NULL;  
14     jint result=-1;  
15     if( (*vm)->GetEnv(vm,(void**)&env , JNI_VERSION_1_4) != JNI_OK)  
16         return result;  
17     jclass HelloJniClazz=(*env)->FindClass(env,"com/example/hellojni/HelloJni");  
18     /* C */  
19     jint r=(*env)->RegisterNatives(env, HelloJniClazz, gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));  
20     /* C++ */  
21     r=AndroidRuntime::registerNativeMethods(env,"com/example/hellojni/HelloJni",gMethods,NELEM(gMethods));  
22     /*或者env->RegisterNatives(HelloJniClazz, gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));*/  
23     if(0 == r)  
24         //注册native函数成功  
25     else  
26         //注册native函数失败  
27     return JNI_VERSION_1_4;  
28 }  
29   
30 void JNI_OnUnload(JavaVM* vm,void* reserved)  
31 {  
32     JNIEnv* env = NULL;  
33     if( (*vm)->GetEnv(vm,(void**)&env , JNI_VERSION_1_4) != JNI_OK)  
34         return;  
35     jclass HelloJniClazz=(*env)->FindClass(env,"com/example/hellojni/HelloJni");  
36     /* C */  
37     jint r=(*env)->UnregisterNatives(env,HelloJniClazz);  
38     /* C++ */  
39     jint r= env->UnregisterNatives(HelloJniClazz)  
40     if(r == 0)  
41         //注销native函数成功  
42     else  
43         //注销native函数失败  
44 }  

 

posted @ 2015-08-19 23:29  f9q  阅读(224)  评论(0编辑  收藏  举报