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, jobject thiz, 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++数据类型转换就不多讲了,参考前面一篇文章的写法。
你可能感兴趣的内容
C++函数指针详解 收藏,2541 浏览
0条评论

dexcoder

这家伙太懒了 <( ̄ ﹌  ̄)>
Owner