加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2d 中使用jni Java 调用 C++ 方法

发布时间:2020-12-14 20:37:41 所属栏目:百科 来源:网络整理
导读:1.首先是LoadLibrary cocos2d中的C++代码会编译成一个.so文件,放在安卓目录下的libs/armeabi 下,然后java会load进来,这步我们不用做了,因为cocos2d已经帮我们做好了。 package cb.CbCCBLE;public class CbCCBLECentralManager { public static final Str

1.首先是LoadLibrary


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



package cb.CbCCBLE;


public class CbCCBLECentralManager {
	
    public static final String TAG = "CbCCBLECentralManager Android";

    
    public native static void bleCenterManagerNotificationChangeState(int oldState,int newState);
    public native static void bleCenterManagerNotificationDidScanOnePeripheral(String peripheralId);
    public native static void bleCenterManagerNotificationDidFinishScanning();
   
}

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


extern "C"
{
    //test
    void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationChangeState(JNIEnv* env,jobject thiz,jint oldState,jint newState)
    {
        CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationChangeState");
     
        CCLOG("oldState:%d,newState:%d",(int)oldState,(int)newState);
    }
    
    
    void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidScanOnePeripheral(JNIEnv* env,jstring peripheralId)
    {
        CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidScanOnePeripheral");
        std::string peripheralId = JniHelper::jstring2string(peripheralId);
        CCLOG("%s",peripheralId.c_str());
    }
    
    void Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidFinishScanning(JNIEnv* env,jobject thiz)
    {
        CCLOG("Java_cb_CbCCBLE_CbCCBLECentralManager_bleCenterManagerNotificationDidFinishScanning");
    }

}

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

http://www.waitingfy.com/archives/1651

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读