Call javascript function from C++

I have a javascript object like this:

var Config = Config || {};

Config.addNumberHints = function(numberAdded)
{
    cc.log("From javascript: " + numberAdded);
};

I want to call the “addNumberHints” function from native c++ code (prefarably using scriptingCore API). I tried to use the following c++ function but it throws exception.

void GameBridgeCPP::addNumberHints(int numberAdded)
{
    ScriptingCore * scriptingCore = ScriptingCore::getInstance();
    
    JSContext * context = scriptingCore->getGlobalContext();
    JS::RootedObject object(context);
    JS::RootedValue owner(context);
    
    jsval * argumentsVector = new jsval[1];
    argumentsVector[0] = INT_TO_JSVAL(numberAdded);
    
    JS_GetProperty(context, object, "Config", &owner);
    scriptingCore->executeFunctionWithOwner(owner, "addNumberHints", 1, argumentsVector);

    delete [] argumentsVector;
}

Please help me out.

@Zinitter @pandamicro @thomasjab @ZippoLag @SonarSystems @zhangxm @ricardo

Sorry to tag you all. I am very desperate :tired_face:. If you can kindly give me any directions I’ll be grateful.

Please somebody help me. :worried:

@mr746866

Do you receive my reply message?

May i know why you need call javascript function from c++?

@Zinitter I need it for changing some parameters after successful in app purchase.

Are you using SDKBOX IAP with Cocos2d-JS?

If not, i think you can try SDKBOX IAP.

You can ask @slackmoehrle @nite for help on the IAP.

I can’t help you on how to call the javascript function from C++ as i also unable to make it work with the limited documents and guide.

This problem is still unsolved

May be you can try doing all the thing in C++ and pass to JS since you able to use jsb.reflection

Are you using Cocos2d-x C++ or JavaScript?

@SonarSystems Cocos2D X JS version.

@Zinitter and rest, I solved it. Turns out I just forgot to add a parameter.

This is the working function.

void GameBridgeCPP::addNumberHints(int numberAdded)
{
    ScriptingCore * scriptingCore = ScriptingCore::getInstance();

    JSContext * context = scriptingCore->getGlobalContext();
    JS::RootedObject object(context, scriptingCore->getGlobalObject());
    JS::RootedValue owner(context);

    jsval * argumentsVector = new jsval[1];
    argumentsVector[0] = INT_TO_JSVAL(numberAdded);

    JS_GetProperty(context, object, "Config", &owner);
    scriptingCore->executeFunctionWithOwner(owner, "addNumberHints", 1, argumentsVector);

    delete [] argumentsVector;
}
1 Like

Glad to see you solved the problems!