Call a Javascript function from an Objective-C class

Call a Javascript function from an Objective-C class
0

Hey guys!

I have followed the instructions here:
https://docs.cocos2d-x.org/creator/manual/en/advanced-topics/oc-reflection.html
https://docs.cocos2d-x.org/creator/manual/en/advanced-topics/java-reflection.html

And I’ve managed to do the following:
:white_check_mark: Call a JAVA method from JS.
:white_check_mark: Call a JS method from JAVA.
:white_check_mark: Call an OBJ-C method from JS.

Now I’m trying to figure out how I can call a JS method from OBJ-C. Is it possible to achieve?

Hi, do you have found a way? :slightly_smiling_face:

Thanks

Stefano

Sure!

Import the following headers in the Obj-C class you’re going to call a JS method:

#import "cocos2d.h"
#import "AppDelegate.h"
#import "cocos/scripting/js-bindings/manual/ScriptingCore.h"

Then you can call it it like this:

- (void)callJS:(NSString *)expressionToEval {
    ScriptingCore *sc = ScriptingCore::getInstance();
    if(sc) {
        const char * strToEval = [expressionToEval cStringUsingEncoding:NSUTF8StringEncoding];
        sc->evalString(strToEval);
    }
}

Make sure your implementation file extension is ClassName.mm rather than ClassName.m.
The .mm extension stands for Objective-C++, when an Obj-C compiler can process C++ classes.

2 Likes

Thanks! Now we try it!