Call java method from c++ with callback parameter

I want to call a java method with callback parameter from c++ code.
Something like below code:

JniHelper::callStaticVoidMethod(helperClassName, “getRequest”, [=](bool success, string responseStr) {
CCLOG(“Test getRequest: %d”, success);
});

Is it possible to do that ???

Thanks in advance.

It’s not dead, but main focus is (unfortunately) on Cocos Creator.

Anyway, it’s possible however not as nice as you’d like.

First, declare in .h file callback definition:

std::function<void(string product)> purchasedProductCallback;

Then, in cpp file, declare method which will call java code:

void NativeHelper::purchaseProduct(string product){
	cocos2d::JniMethodInfo t;
	if (cocos2d::JniHelper::getStaticMethodInfo(t, AppActivityClassName, "purchaseProduct", "(Ljava/lang/String;)V")){

		jstring stringArg = t.env->NewStringUTF(product.c_str());
		t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg);

		t.env->DeleteLocalRef(t.classID);
		t.env->DeleteLocalRef(stringArg);
	}
}

In Java define your method:

public static void purchaseProduct(final String product) {
    //...
}

Also define callback:

public static native void purchasedProductCallback(String product);

Then later on in Java code call the callback (in my case when product was purchased successfully):

Cocos2dxHelper.runOnGLThread(new Runnable() {
    @Override
    public void run() {
        purchasedProductCallback(product);
    }
});

Coming back to c++:

extern "C"
{
    JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_purchasedProductCallback(JNIEnv* env, jobject thiz, jstring product);
}

JNIEXPORT void JNICALL Java_org_cocos2dx_cpp_AppActivity_purchasedProductCallback(JNIEnv* env, jobject thiz, jstring product){
    std::string str = JniHelper::jstring2string(product);
    auto helper = NativeHelper::getInstance();
	if(helper->purchasedProductCallback != nullptr){
    	helper->purchasedProductCallback(str);
    }
}

Now you can use it in your scene:

setonEnterTransitionDidFinishCallback([&](){
    auto helper = NativeHelper::getInstance();
    helper->purchasedProductCallback = std::bind(&InAppScene::purchasedProductCallback, this, std::placeholders::_1);
});

setonExitTransitionDidStartCallback([&]() {
    auto helper = NativeHelper::getInstance();
    helper->purchasedProductCallback = nullptr;
});

It’s important to clear out callback when leaving a scene to avoid memory crashes.

Somewhere in the same scene:

NativeHelper::getInstance()->purchaseProduct("foo");
2 Likes

@piotrros
Thanks a lot