标签:binding html stat javac cti scripting delegate c_str property
1、java中的写法
/* * XConnectPlugin.java * * Created on: 2014年4月30日 * Author: lswdonald9@gmail.com */ package org.cocos2dx.commonSDK; import android.util.Log; public class XConnectPlugin { public static void start(String str) { Log.d("mylog ", "str>>" + str); } }
2、C++中的写法
头文件(XInterface.h)声明方法:
/* * XInterface.h * * Created on: 2014年4月30日 * Author: lswdonald9@gmail.com */ #ifndef XINTERFACE_H_ #define XINTERFACE_H_ #include "string" class XInterface { public: static void start(const char* ct); }; #endif /* XINTERFACE_H_ */
XInterface.cpp中写法:
/* * XInterface.cpp * * Created on: 2014年4月30日 * Author: lswdonald9@gmail.com */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include "XInterface.h" #include "platform/android/jni/JniHelper.h" #include <jni.h> #include <android/log.h> #include "ScriptingCore.h" XInterface::XInterface() { } XInterface::~XInterface() { } const char* XJavaClassName = "org/cocos2dx/commonSDK/XConnectPlugin"; void XInterface::start(const char* cLevel) { JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, XJavaClassName, "start", "(Ljava/lang/String;)V")) { if (cLevel) { jstring jLevel = t.env->NewStringUTF(cLevel); t.env->CallStaticVoidMethod(t.classID, t.methodID, jLevel); t.env->DeleteLocalRef(jLevel); } t.env->DeleteLocalRef(t.classID); } } #endif
3、以下部分是,在SpritMonkey中注冊C++方法到javascript中
js_bindings_X.cpp
/* * jsbindingsX.cpp * * Created on: 2014年4月30日 * Author: lswdonald9@gmail.com */ #include "ScriptingCore.h" #include "XInterface.h" JSBool JSB_X_start(JSContext *cx, uint32_t argc, jsval *vp){ std::string str; if(argc == 1) { jsval *argv = JS_ARGV(cx, vp); jsval_to_std_string(cx, argv[0], &str); XInterface::start(str.c_str()); } return JS_TRUE; } void register_X_js(JSContext* cx, JSObject* global){ jsval nsval; JSObject *XJsbObject; JS_GetProperty(cx, global, "XJsb", &nsval); if (nsval == JSVAL_VOID) { XJsbObject = JS_NewObject(cx, NULL, NULL, NULL); nsval = OBJECT_TO_JSVAL(XJsbObject); JS_SetProperty(cx, global, "XJsb", &nsval); } else JS_ValueToObject(cx, nsval, &XJsbObject); JS_DefineFunction(cx, XJsbObject, "start", JSB_X_start, 1, JSPROP_READONLY | JSPROP_PERMANENT); }
var XJsb = XJsb || { start : function () { } };注意。这里的XJsb跟c++ 中的register_x_js 保持一致.
然后在,须要调用的地方。触发:
XJsb.start("from javaScript");须要注意,在AppDelegate.cpp中。增加
extern void register_X_js(JSContext* cx, JSObject* global);和
ScriptingCore* sc = ScriptingCore::getInstance(); sc->addRegisterCallback(register_X_js);在Android.mk中的LOCAL_SRC_FILES加入:
LOCAL_SRC_FILES := ../../Classes/XInterface.cpp ../../Classes/js_bindings_X.cpp
最后的结果就出来了:from javaScript
cocos2d-html5 javascript 通过C++绑定,调用java方法
标签:binding html stat javac cti scripting delegate c_str property
原文地址:http://www.cnblogs.com/zhchoutai/p/7191490.html