Problem calling js function from C++

I am new to cocos2d-x jsb, and I got a problem call js function from c++
here is my code in c++:

void cToJs::call(void) {
ScriptingCore* sc =ScriptingCore::getInstance();

jsval nsval;
    if(!sc){
        CCLog(“sc is NULL”);
    }
    if(!sc->getGlobalContext())
    {
        CCLog(“sc->getGlobalContext() is NULL”);
    }
    if(!sc->getGlobalObject())
    {
        CCLog(“sc->getGlobalObject is NULL”);
    }
    JS_GetProperty(sc->getGlobalContext(), sc->getGlobalObject(),“msgFromC”, &nsval);
    if (nsval !=JSVAL_VOID) {
        sc->executeFunctionWithOwner(nsval,“call”);
        CCLog(“js function excuted”);
    }else{
        CCLog(“can not find js class”);
    }
}

and here is my js code:

var msgFromC = cc.Node.extend({
  ctor: function() {
    this._super();
  },
  call: function(msg) {
    cc.log("I got a message back from C++: " + msg);
  }
});

when I invoke:
cToJs *p = new cToJs();
p->call();

the log shows:

D/cocos2d-x debug info(18621): sc->getGlobalContext() is NULL
D/cocos2d-x debug info(18621): sc->getGlobalObject is NULL
A/libc(18621): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 18621

what is wrong, can anyone help?

When do you invoke this function ? Maybe before the initialization of ScriptingCore ?

Besides, the logic of js function call is not correct, msgFromC is the class, and call is its property function, so sc->executeFunctionWithOwner(nsval,"call"); won’t find the call function, you should do the following to get it work:

var MsgFromC = cc.Node.extend({
  ctor: function() {
    this._super();
  },
  call: function(msg) {
    cc.log("I got a message back from C++: " + msg);
  }
});

var msgFromC = new MsgFromC();

It crashes cause your global context and so your global object is NULL but you still call:

JS_GetProperty(sc->getGlobalContext(), sc->getGlobalObject(),"msgFromC", &nsval);

You are testing for NULL pointers, but are still using them in the above call. If they are NULL, don’t do that :frowning:

Your basic problem is, that you forgot to start the scripting core with

sc->start();

So start it after getting an instance of the scripting core:

ScriptingCore* sc =ScriptingCore::getInstance();
sc->start();

thanks, problem solved
because I call cToJs->call() right after android onCreate() method.
but at that time, game lib is not called, so sc is not started.

I call cToJs->call() after game start, and change the js code as you mentioned, everything works fine

thankyou for your reply, problem solved, you are right :slight_smile:

Hi @spin0303,

The solution you have mentioned here is old as in current version of cocos creator i didn’t find these above function. Do you have latest code for current version of cocos creator ?