使用的是Cocos creator 2.4.3版本;直接贴代码,结构如下:
在CocosDashboard\resources.editors\Creator\2.4.3\resources\cocos2d-x\cocos\scripting\js-bindings\manual 文件夹下创建
jsb_test.hpp和jsb_test.cpp两个文件。
jsb_test.hpp内容如下:
#pragma once
namespace se {
class Object;
}
bool register_all_testio(se::Object* obj);
jsb_test.cpp代码如下:
#include "jsb_test.hpp"
#include "cocos/scripting/js-bindings/manual/jsb_conversions.hpp"
static bool jsb_Test(se::State &s)
{
CC_UNUSED std::string ok = "";
std::string result = "这是一条测试";//这里可以调用其他的C++逻辑,简写了。
ok = std_string_to_seval(result, &s.rval()); //返回string
return true;
}
SE_BIND_FUNC(jsb_Test)
bool register_all_testio(se::Object *obj)
{
se::Value nsVal;
if (!obj->getProperty("Test", &nsVal))
{
se::HandleObject jsobj(se::Object::createPlainObject());
nsVal.setObject(jsobj);
obj->setProperty("Test", nsVal);
}
se::Object *ns = nsVal.toObject();
ns->defineFunction("test", _SE(jsb_Test));
//js中直接Test.test();调用
return true;
}
然后在CocosDashboard\resources.editors\Creator\2.4.3\resources\cocos2d-x\cocos\scripting\js-bindings\manual\jsb_module_register.cpp中添加如下代码。
#include "cocos/scripting/js-bindings/manual/jsb_test.hpp"
// 注册模块
se->addRegisterCallback(register_all_testio);
最坑的是对应工程的CreatorDemo\build\jsb-link\frameworks\runtime-src\Classes\jsb_module_register.cpp也要添加上面的代码(以我的工程为例,大家灵活应对)。
CocosDashboard\resources.editors\Creator\2.4.3\resources\cocos2d-x\cocos\Android.mk文件添加相应的cpp文件,生成so打包就可以使用了。
LOCAL_SRC_FILES += \
scripting/js-bindings/manual/jsb_test.cpp
至此简单的手动绑定就实现了,复杂的可以查看手册实现。
https://docs.cocos.com/creator/manual/zh/advanced-topics/JSB2.0-learning.html
https://docs.cocos.com/creator/manual/zh/advanced-topics/jsb-manual-binding.html?h=jsb