cocos2d-x使用jni java调用c++方法(java 调 c++)

来源:互联网 发布:产品网站源码 编辑:程序博客网 时间:2024/05/24 04:53

1.首先是LoadLibrary


cocos2d中的C++代码会编译成一个.so文件,放在安卓目录下的libs/armeabi 下,然后Java会load进来,这步我们不用做了,因为cocos2d已经帮我们做好了。



[java] view plain copy
  1. package cb.CbCCBLE;  
  2.   
  3.   
  4. public class CbCCBLECentralManager {  
  5.       
  6.     public static final String TAG = "CbCCBLECentralManager Android";  
  7.   
  8.       
  9.     public native static void bleCenterManagerNotificationChangeState(int oldState, int newState);  
  10.     public native static void bleCenterManagerNotificationDidScanOnePeripheral(String peripheralId);  
  11.     public native static void bleCenterManagerNotificationDidFinishScanning();  
  12.      
  13. }  

先看下java的是如何些的,java中只是定义了几个native的方法,然后java中调用这些方法即可。主要看下C++是如何实现的。这里就举例上面的3个例子好了。


[cpp] view plain copy
  1. extern "C"  
  2. {  
  3.     //test  
  4.     void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationChangeState(JNIEnv* env, jobject thiz, jint oldState, jint newState)  
  5.     {  
  6.         CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationChangeState");  
  7.        
  8.         CCLOG("oldState:%d, newState:%d", (int)oldState, (int)newState);  
  9.     }  
  10.       
  11.       
  12.     void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidScanOnePeripheral(JNIEnv* env, jobject thiz, jstring peripheralId)  
  13.     {  
  14.         CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidScanOnePeripheral");  
  15.         std::string peripheralId = JniHelper::jstring2string(peripheralId);  
  16.         CCLOG("%s", peripheralId.c_str());  
  17.     }  
  18.       
  19.     void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidFinishScanning(JNIEnv* env, jobject thiz)  
  20.     {  
  21.         CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidFinishScanning");  
  22.     }  
  23.   
  24. }  

注意到我们c++的代码都是写在extern "C"中,方法名字特别长,但是是有格式的,Java开头,然后是包名字+类名字+方法名字,都是用'_'隔开。传过来的参数就是跟在后面即可。里面jni数据类型到C++数据类型转换就不多讲了,参考前面一篇文章的写法
原创粉丝点击