Ok, here is example (not tested):
// this function will be called from js
bool function_called_from_js(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
// we expect only one argument
if (argc == 1) {
// ergument should be string
if (!args.get(0).isString())
{
ok = false;
}
JSB_PRECONDITION2(ok, cx, false, "function_called_from_js : Error processing arguments");
string argument;
jsval_to_std_string(cx, args.get(0), &argument);
CCLOG("function_called_from_js %s", argument.c_str());
// here we call Java static function
JniHelper::callStaticVoidMethod(
"org/cocos2dx/lib/Cocos2dxHelper", // class package
"call_from_cpp", // static function in Java
"from C++" // string argument
);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "function_called_from_js : wrong number of arguments");
return false;
}
void register_js_function(JSContext *cx, JS::HandleObject global)
{
JS::RootedObject global_obj(cx, global);
JS_DefineFunction(cx,
global_obj, // add function to global object
"function_called_from_js", // function name
function_called_from_js, // C++ handler of js function
1, // number of arguments
JSPROP_READONLY | JSPROP_PERMANENT
);
}
Add this to in AppDelegate.cpp:
// in AppDelegate.cpp add to bool AppDelegate::applicationDidFinishLaunching() method:
sc->addRegisterCallback(register_js_function);
Java code
// Java code of cocos\platform\android\java\src\org\cocos2dx\lib\Cocos2dxHelper.java
// native function declaration, it's implemented in C++ code
public static native void test_cpp_func(String str);
public static void call_from_cpp() {
Log.d("Cocos2dxHelper", "Yahhoooo! Java code is executed!");
test_cpp_func("Hello from Java!"); // call native C++ function
}
C++ function which will be called from Java
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/jni/JniHelper.h"
extern "C"{
// full name is package path + function name
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_test_cpp_func(JNIEnv *env, jobject thiz, jstring jstr) {
std::string str = JniHelper::jstring2string(jstr);
CCLOG("test_cpp_func: %s", str.c_str());
}
}
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
JS test code:
function_called_from_js("test");
Flow:
from JS we call function_called_from_js, in C++ will be called bool function_called_from_js(JSContext *cx, uint32_t argc, jsval *vp); which calls Java call_from_cpp function which calls C++ test_cpp_func function and Java_org_cocos2dx_lib_Cocos2dxHelper_test_cpp_func will be called as last.