Tutorial: JSB 2.0

The Abstraction Layer of Script Engine

Architecture

JSB2.0-Architecture

Macro

The abstraction layer is bound to take more CPU execution time than using the JS engine API directly. How to minimize the overhead of the abstraction layer becomes the first goal of the design.

Most of work in JS binding is actually setting JS related operations with CPP callbacks and associating CPP object within the callback function. In fact, it mainly contains the following two situation:

  • Register JS functions (including global functions, class constructors, class destructors, class member functions, and class static member functions), binding revenant CPP callbacks
  • Register accessors for JS properties, bind CPP callbacks for reading and writing properties respectively

How to achieve the minimum overhead for the abstract layer and expose the unified API?

For example, to register a JS function in CPP, there are different definitions in JavaScriptCore, SpiderMonkey, V8, ChakraCore as follows:

  • JavaScriptCore

    1. JSValueRef JSB_foo_func(
    2. JSContextRef _cx,
    3. JSObjectRef _function,
    4. JSObjectRef _thisObject,
    5. size_t argc,
    6. const JSValueRef _argv[],
    7. JSValueRef* _exception
    8. );
  • SpiderMonkey

    1. bool JSB_foo_func(
    2. JSContext* _cx,
    3. unsigned argc,
    4. JS::Value* _vp
    5. );
  • V8

    1. void JSB_foo_func(
    2. const v8::FunctionCallbackInfo<v8::Value>& v8args
    3. );
  • ChakraCore

    1. JsValueRef JSB_foo_func(
    2. JsValueRef _callee,
    3. bool _isConstructCall,
    4. JsValueRef* _argv,
    5. unsigned short argc,
    6. void* _callbackState
    7. );

We evaluated several options and eventually decided to use macros to reduce the differences between the definition and parameter types of different JS engine callbacks, regardless of which engine is used, and developers could use an unified callback definition. We refer to the definition of Lua callback function. The definition of all JS to CPP callback functions in the abstract layer is defined as:

  1. bool foo(se::State& s)
  2. {
  3. ...
  4. ...
  5. }
  6. SE_BIND_FUNC(foo) // Binding a JS function as an example

After a developer has bound a JS function, remember to wrap the callback function with the macros which start with SE_BIND_. Currently, we provide the following macros:

  • SE_BIND_PROP_GET: Wrap a JS object property read callback function
  • SE_BIND_PROP_SET: Wrap a JS object property written callback function
  • SE_BIND_FUNC_AS_PROP_GET: Wrap a member function as a JS property getter callback function.
  • SE_BIND_FUNC_AS_PROP_SET: Wrap a member function as a JS property setter callback function
  • SE_BIND_FUNC: Wrap a JS function that can be used for global functions, class member functions or class static functions
  • SE_BIND_FUNC_FAST: Wrap a parameter-less C++ function into a JS function in a faster way.
  • SE_DECLARE_FUNC: Declare a JS function, generally used in the header file
  • SE_BIND_CTOR: Wrap a JS constructor
  • SE_BIND_SUB_CLS_CTOR: Wrap the constructor of a JS subclass.
  • SE_BIND_FINALIZE_FUNC: Wrap the finalize function of a JS object, finalize function is invoked when the object is released by Garbage Collector
  • SE_DECLARE_FINALIZE_FUNC: Declares the finalize function of a JS object
  • _SE: The macro for making callback be recognized by different JS engine. Note that the first character is underscored, similar to _T ('xxx') in Windows for wrapping Unicode or MultiBytes string

    Note: the first character is an underscore, similar to _T("xxx") used in Windows to wrap Unicode or MultiBytes strings.

API

CPP Namespace

All types of the abstraction layer are under the se namespace, which is an abbreviation of ScriptEngine.

Types

se::ScriptEngine

se::ScriptEngine is the JS engine administrator, responsible for JS engine initialization, destruction, restart, native module registration, loading scripts, doing garbage collection, JS exception cleanup and whether to enable the debugger. It is a singleton that could be accessed via se::ScriptEngine::getInstance().

se::Value

se::Value can be understood as a JS variable reference in the CPP layer. There are six types of JS variables: object, number, bigint string, boolean, null, undefined, so se::Value uses an union to include object, number, string, boolean, int64_t these 5 kinds of value types, non-value types like null and undefined can be represented by _type directly.

  1. namespace se {
  2. class Value {
  3. enum class Type : char
  4. {
  5. Undefined = 0,
  6. Null,
  7. Number,
  8. Boolean,
  9. String,
  10. Object,
  11. BigInt, // mostly used to store a 8 bytes pointer
  12. };
  13. ...
  14. ...
  15. private:
  16. union {
  17. bool _boolean;
  18. double _number;
  19. std::string* _string;
  20. Object* _object;
  21. int64_t _bigint;
  22. } _u;
  23. Type _type;
  24. ...
  25. ...
  26. };
  27. }

If se::Value stores the underlying data types, such as number, string, boolean, which is directly stored by value copy.
The storage of object is special because it is a weak reference to JS objects via se::Object*.

se::Object

se::Object extends from se::RefCounter which is a class for reference count management. Currently, only se::Object inherits from se::RefCounter in the abstraction layer.

As we mentioned in the last section, se::Object is a weak reference to the JS object, therefore I will explain why it’s a weak reference.

Reason 1: The requirement of controlling the life cycle of CPP objects by JS objects

After creating a Sprite in the script layer via var xhr = new XMLHttpRequest();, we create a se::Object in the constructor callback and leave it in a global map (NativePtrToObjectMap), this map is used to query the XMLHttpRequest* to get the corresponding JS object se::Object*.

  1. /// native/cocos/bindings/manual/jsb_xmlhttprequest.cpp
  2. static bool XMLHttpRequest_constructor(se::State& s)
  3. {
  4. XMLHttpRequest* cobj = JSB_ALLOC(XMLHttpRequest);
  5. s.thisObject()->setPrivateData(cobj);
  6. return true;
  7. }
  8. SE_BIND_CTOR(XMLHttpRequest_constructor, __jsb_XMLHttpRequest_class, XMLHttpRequest_finalize)
  9. /// native/cocos/bindings/jswrapper/v8/Object.cpp
  10. void Object::setPrivateObject(PrivateObjectBase *data) {
  11. // ...
  12. if (data != nullptr) {
  13. _privateData = data->getRaw();
  14. NativePtrToObjectMap::emplace(_privateData, this);
  15. } else {
  16. _privateData = nullptr;
  17. }
  18. }

Imagine if you force se::Object to be a strong reference to a JS object that leaves JS objects out of GC control and the finalize callback will never be fired because se::Object is always present in map which will cause memory leak.

Reason 2: More flexible, supporting strong reference by calling the se::Object::root method manually

se::Object provides root/unroot method for developers to invoke, root will put JS object into the area not be scanned by the GC. After calling root, se::Object* is a strong reference to the JS object. JS object will be put back to the area scanned by the GC only when se::Object is destructed or unroot is called to make root count to zero.

Under normal circumstances, if the C++ object is not a subclass of cc::Ref, the C++ object will be used to control the life cycle of the JS object in binding. Binding the engine modules, like Spine, DragonBones, Box2d and other third-party libraries uses this method. When the C++ object is released, it is necessary to find the corresponding se::Object in the NativePtrToObjectMap, then manually unroot and decRef it. Take the binding of spTrackEntry in Spine as an example:

  1. spTrackEntry_setDisposeCallback([](spTrackEntry* entry){
  2. se::Object* seObj = nullptr;
  3. auto iter = se::NativePtrToObjectMap::find(entry);
  4. if (iter != se::NativePtrToObjectMap::end())
  5. {
  6. // Save se::Object pointer for being used in cleanup method.
  7. seObj = iter->second;
  8. // Unmap native and js object since native object was destroyed.
  9. // Otherwise, it may trigger 'assertion' in se::Object::setPrivateData later
  10. // Since native obj is already released and the new native object may be assigned with the same address.
  11. se::NativePtrToObjectMap::erase(iter);
  12. } else {
  13. return;
  14. }
  15. auto cleanup = [seObj](){
  16. auto se = se::ScriptEngine::getInstance();
  17. if (!se->isValid() || se->isInCleanup())
  18. return;
  19. se::AutoHandleScope hs;
  20. se->clearException();
  21. // The mapping of native object & se::Object was cleared in above code.
  22. // The private data (native object) may be a different object associated with other se::Object.
  23. // Therefore, don't clear the mapping again.
  24. seObj->clearPrivateData(false);
  25. seObj->unroot(); // Unroot, making JS objects subject to GC management
  26. seObj->decRef(); // Release se::Object
  27. };
  28. if (!se::ScriptEngine::getInstance()->isGarbageCollecting()) {
  29. cleanup();
  30. }
  31. else {
  32. CleanupTask::pushTaskToAutoReleasePool(cleanup);
  33. }
  34. });

C++ Object lifecycle management

Prior to 3.6, the destructor callback _finalize would call delete or release to release the corresponding C++ object, depending on the object type and whether it existed in se::NonRefNativePtrCreatedByCtorMap. Since 3.6, the _finalize callback has been deprecated and left empty for the time being for debugging purposes. se::Object establishes a lifecycle association with C++ objects via se::PrivateObjectBase objects. The three subclasses of se::PrivateObjectBase correspond to different release policies.

  • se::CCSharedPtrPrivateObject<T>

uses cc::IntrusivePtr to store pointers to C++ objects, requiring that the C++ class inherits from cc::RefCounted. Where cc::IntrusivePtr is a smart pointer type that automatically increments or decrements the reference count of cc::RefCounted. When the reference count is 0, destructions are triggered.

  • se::SharedPrivateObject<T>

Use std::shared_ptr to store C++ object pointers, requiring that C++ classes do not inherit from cc::RefCounted. Due to the nature of shared_ptr itself, all strong references are required to be shared_ptr. Destructing C++ objects is triggered when all shared_ptrs are destroyed.

  • se::RawRefPrivateObject<T>

Uses a bare pointer, which defaults to a weak reference to a C++ object. It can be converted to a strong reference by calling tryAllowDestroyInGC. As a weak reference, GC does not trigger destructing the object.

Associate native objects.

After 3.6 se::Object::setPrivateData(void *) is extended to:

  1. template <typename T>
  2. inline void setPrivateData(T *data);

can automatically create SharedPrivateObject or CCSharedPtrPrivateObject based on type information, but does not support RawRefPrivateObject.

We can use setPrivateObject to display the type of the specified PrivateObject:

  1. // se::SharedPrivateObject<T>
  2. obj->setPrivateObject(se::shared_private_object(v));
  3. // se::CCSharedPtrPrivateObject<T>
  4. obj->setPrivateObject(se::ccshared_private_object(v));
  5. // se::RawRefPrivateObject<T>
  6. obj->setPrivateObject(se::rawref_private_object(v));

Object Types

The creation of native binding object has been hidden in the SE_BIND_CTOR and SE_BIND_SUB_CLS_CTOR macros, if developers need to use the se::Object in the binding callback, just get it by invoking s.thisObject(). Where s is se::State& which will be described in the following chapters.

In addition, se::Object currently supports the manual creation of the following objects:

  • Plain Object: Created by se::Object::createPlainObject, similar to var a = {}; in JS
  • Array Object: Created by se::Object::createArrayObject, similar to var a = []; in JS
  • Uint8 Typed Array Object: Created by se::Object::createTypedArray, like var a = new Uint8Array(buffer); in JS
  • Array Buffer Object: Created by se::Object::createArrayBufferObject similar to var a = new ArrayBuffer(len); in JS

The Release of The Objects Created Manually

se::Object::createXXX is unlike the create method in Cocos Creator, the abstraction layer is a completely separate module which does not rely on the autorelease mechanism in Cocos Creator. Although se::Object also inherits the reference count class se::RefCounter, developers need to handle the release for objects created manually.

  1. se::Object* obj = se::Object::createPlainObject();
  2. ...
  3. ...
  4. obj->decRef(); // Decrease the reference count to avoid memory leak
  • If using manual creation of objects in complex logic, developers often forget to deal with decRef in different conditions

    1. bool foo()
    2. {
    3. se::Object* obj = se::Object::createPlainObject();
    4. if (var1)
    5. return false; // Return directly, forget to do 'decRef' operation
    6. if (var2)
    7. return false; // Return directly, forget to do 'decRef' operation
    8. ...
    9. ...
    10. obj->decRef();
    11. return true;
    12. }

    Plus adding decRef to different return condition branches can result in logically complex and difficult to maintain, and it is easy to forget about decRef if you make another return branch later.

  • If the JS engine did a GC operationJS engine right after se::Object::createXXX, which will result in the se::Object reference to an illegal pointer, the program may crash.

In order to solve the above problems, the abstraction layer defines a type that assists in the management of manually created objects, namely se::HandleObject.

se::HandleObject is a helper class for easier management of the release (decRef), root, and unroot operations of manually created se::Object objects.

The following two code snippets are equivalent, the use of se::HandleObject significantly smaller amount of code, and more secure.

  1. {
  2. se::HandleObject obj(se::Object::createPlainObject());
  3. obj->setProperty(...);
  4. otherObject->setProperty("foo", se::Value(obj));
  5. }

Is equal to:

  1. {
  2. se::Object* obj = se::Object::createPlainObject();
  3. obj->root(); // Root the object immediately to prevent the object being garbage collected.
  4. obj->setProperty(...);
  5. otherObject->setProperty("foo", se::Value(obj));
  6. obj->unroot(); // Call unroot while the object is needed anymore.
  7. obj->decRef(); // Decrease the reference count to avoid memory leak.
  8. }

NOTES:

  1. Do not try to use se::HandleObject to create a native binding object. In the JavaScript controls of C++ mode, the release of the bound object will be automatically handled by the abstraction layer. In the C++ controls JavaScript mode, the previous chapter has already described it.
  2. The se::HandleObject object can only be allocated on the stack, and a se::Object pointer must be passed in.

se::Class

se::Class is used to expose CPP classes to JS, it creates a constructor function in JS that has a corresponding name.

It has the following methods:

  • static se::Class* create(className, obj, parentProto, ctor): Creating a Class. If the registration is successful, it is then possible to create an object by calling var xxx = new SomeClass (); in the JavaScript layer.
  • bool defineFunction(name, func): Define a member function for a class.
  • bool defineProperty(name, getter, setter): Define a property accessor for a class.
  • bool defineStaticFunction(name, func): Define a static function for a class, the JavaScript function could be accessed by SomeClass.foo() rather than calling var obj = new SomeClass(); obj.foo(), this means it’s a class method instead of an instance method.
  • bool defineStaticProperty(name, getter, setter): Define a static property accessor which could be invoked by SomeClass.propertyA, it’s nothing about instance object.
  • bool defineFinalizeFunction(func): Define the finalize callback function after JS object is garbage collected.
  • bool install(): Install a class JS engine.
  • Object* getProto(): Get the prototype of JS constructor installed, similar to Foo.prototype of function Foo(){} in JS.
  • const char* getName() const: Get the class name which is also the name of JS constructor.

NOTE: you do not need to release memory manually after se::Class type is created, it will be automatically encapsulated layer.

You could look through the API documentation or code comments for more specific API instructions.

se::AutoHandleScope

The se::AutoHandleScope object type is purely a concept introduced to address V8 compatibility issues. In V8, any action that calls v8::Local<> on a CPP function that needs to trigger a JS related operation, such as calling a JS function, accessing a JS property, etc, requires a v8::HandleScope function be invoked before calling these operations, otherwise it will cause the program to crash.

So the concept of se::AutoHandleScope was introduced into the abstraction layer, which is implemented only on V8, and the other JS engines are currently just empty implementations.

Developers need to remember that in any code execution from CPP, you need to declare a se::AutoHandleScope before calling JS’s logic. For example:

  1. class SomeClass {
  2. void update(float dt) {
  3. se::ScriptEngine::getInstance()->clearException(); // Clear JS exceptions
  4. se::AutoHandleScope hs; // Declare a handle scope, it's needed for V8
  5. se::Object* obj = ...;
  6. obj->setProperty(...);
  7. ...
  8. ...
  9. obj->call(...);
  10. }
  11. };

se::State

In the previous section, we have mentioned the se::State type, which is an environment in the binding callback. We can get the current CPP pointer, se::Object object pointer, parameter list and return value reference through se::State argument.

  1. bool foo(se::State& s)
  2. {
  3. // Get native object pointer bound with the current JS object.
  4. SomeClass* cobj = (SomeClass*)s.nativeThisObject();
  5. // Get se::Object pointer that represents the current JS object.
  6. se::Object* thisObject = s.thisObject();
  7. // Get argument list of the current function.
  8. const se::ValueArray& args = s.args();
  9. // Set return value for current function.
  10. s.rval().setInt32(100);
  11. // Return true to indicate the function is executed successfully.
  12. return true;
  13. }
  14. SE_BIND_FUNC(foo)

Does The Abstraction Layer Depend on Cocos Creator?

No, it doesn’t.

This abstraction layer was originally designed as a stand-alone module which is completely independent of Cocos Creator engine. Developers can copy the abstraction layer code in cocos/scripting/jswrapper directory and paste them to other projects directly.

Manual Binding

Define A Callback Function

  1. static bool Foo_balabala(se::State& s)
  2. {
  3. const auto& args = s.args();
  4. int argc = (int)args.size();
  5. if (argc >= 2) // Limit the number of parameters must be greater than or equal to 2, or throw an error to the JS layer and return false. {
  6. ...
  7. ...
  8. return true;
  9. }
  10. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 2) ;
  11. return false;
  12. }
  13. // If binding a function, we use SE_BIND_FUNC macro. For binding a constructor, destructor, subclass constructor, please use SE_BIND_balabala macros memtioned above.
  14. SE_BIND_FUNC(Foo_balabala)

Set A Property Value for JS object

  1. se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easier demonstration.
  2. globalObj->setProperty("foo", se::Value(100)); // Set a property called `foo` with a value of 100 to the global object.

Next, use the foo global variable in JS directly.

  1. log("foo value: " + foo); // Print `foo value: 100`.

Set A Property Accessor for JS Object

  1. // The read callback of "foo" property of the global object
  2. static bool Global_get_foo(se::State& s)
  3. {
  4. NativeObj* cobj = (NativeObj*)s.nativeThisObject();
  5. int32_t ret = cobj->getValue();
  6. s.rval().setInt32(ret);
  7. return true;
  8. }
  9. SE_BIND_PROP_GET(Global_get_foo)
  10. // The write callback of "foo" property of the global object
  11. static bool Global_set_foo(se::State& s)
  12. {
  13. const auto& args = s.args();
  14. int argc = (int)args.size();
  15. if (argc >= 1)
  16. {
  17. NativeObj* cobj = (NativeObj*)s.nativeThisObject();
  18. int32_t arg1 = args[0].toInt32();
  19. cobj->setValue(arg1);
  20. // Do not need to call "s.rval().set(se::Value::Undefined)" for functions without return value.
  21. return true;
  22. }
  23. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1) ;
  24. return false;
  25. }
  26. SE_BIND_PROP_SET(Global_set_foo)
  27. void some_func()
  28. {
  29. se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easier demonstration.
  30. globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // Use _SE macro to package specific function name.
  31. }

Define A Function for JS Object

  1. static bool Foo_function(se::State& s)
  2. {
  3. ...
  4. ...
  5. }
  6. SE_BIND_FUNC(Foo_function)
  7. void some_func()
  8. {
  9. se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // We get the global object just for easier demonstration.
  10. globalObj->defineFunction("foo", _SE(Foo_function)); // Use _SE macro to package specific function name.
  11. }

Register A CPP Class to JS Virtual Machine

  1. static se::Object* __jsb_ns_SomeClass_proto = nullptr;
  2. static se::Class* __jsb_ns_SomeClass_class = nullptr;
  3. namespace ns {
  4. class SomeClass
  5. {
  6. public:
  7. SomeClass()
  8. : xxx(0)
  9. {}
  10. void foo() {
  11. printf("SomeClass::foo\n");
  12. Director::getInstance()->getScheduler()->schedule([this](float dt){
  13. static int counter = 0;
  14. ++counter;
  15. if (_cb != nullptr)
  16. _cb(counter);
  17. }, this, 1.0f, CC_REPEAT_FOREVER, 0.0f, false, "iamkey");
  18. }
  19. static void static_func() {
  20. printf("SomeClass::static_func\n");
  21. }
  22. void setCallback(const std::function<void(int)>& cb) {
  23. _cb = cb;
  24. if (_cb != nullptr)
  25. {
  26. printf("setCallback(cb)\n");
  27. }
  28. else
  29. {
  30. printf("setCallback(nullptr)\n");
  31. }
  32. }
  33. int xxx;
  34. private:
  35. std::function<void(int)> _cb;
  36. };
  37. } // namespace ns {
  38. static bool js_SomeClass_finalize(se::State& s)
  39. {
  40. ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject();
  41. delete cobj;
  42. return true;
  43. }
  44. SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize)
  45. static bool js_SomeClass_constructor(se::State& s)
  46. {
  47. ns::SomeClass* cobj = new ns::SomeClass();
  48. s.thisObject()->setPrivateData(cobj);
  49. return true;
  50. }
  51. SE_BIND_CTOR(js_SomeClass_constructor, __jsb_ns_SomeClass_class, js_SomeClass_finalize)
  52. static bool js_SomeClass_foo(se::State& s)
  53. {
  54. ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject();
  55. cobj->foo();
  56. return true;
  57. }
  58. SE_BIND_FUNC(js_SomeClass_foo)
  59. static bool js_SomeClass_get_xxx(se::State& s)
  60. {
  61. ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject();
  62. s.rval().setInt32(cobj->xxx);
  63. return true;
  64. }
  65. SE_BIND_PROP_GET(js_SomeClass_get_xxx)
  66. static bool js_SomeClass_set_xxx(se::State& s)
  67. {
  68. const auto& args = s.args();
  69. int argc = (int)args.size();
  70. if (argc > 0)
  71. {
  72. ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject();
  73. cobj->xxx = args[0].toInt32();
  74. return true;
  75. }
  76. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
  77. return false;
  78. }
  79. SE_BIND_PROP_SET(js_SomeClass_set_xxx)
  80. static bool js_SomeClass_static_func(se::State& s)
  81. {
  82. ns::SomeClass::static_func();
  83. return true;
  84. }
  85. SE_BIND_FUNC(js_SomeClass_static_func)
  86. bool js_register_ns_SomeClass(se::Object* global)
  87. {
  88. // Make sure the namespace exists
  89. se::Value nsVal;
  90. if (!global->getProperty("ns", &nsVal))
  91. {
  92. // If it doesn't exist, create one. Similar as "var ns = {};" in JS.
  93. se::HandleObject jsobj(se::Object::createPlainObject());
  94. nsVal.setObject(jsobj);
  95. // Set the object to the global object with the property name `ns`.
  96. global->setProperty("ns", nsVal);
  97. }
  98. se::Object* ns = nsVal.toObject();
  99. // Create a se::Class object, developers do not need to consider the release of the se::Class object, which is automatically handled by the ScriptEngine.
  100. auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // If the registered class doesn't need a constructor, the last argument can be passed in with nullptr, it will make "new SomeClass();" illegal.
  101. // Define member functions, member properties.
  102. cls->defineFunction("foo", _SE(js_SomeClass_foo));
  103. cls->defineProperty("xxx", _SE(js_SomeClass_get_xxx), _SE(js_SomeClass_set_xxx));
  104. // Define finalize callback function
  105. cls->defineFinalizeFunction(_SE(js_SomeClass_finalize));
  106. // Install the class to JS virtual machine
  107. cls->install();
  108. // JSBClassType::registerClass is a helper function in the Cocos Creator native binding code, which is not a part of the ScriptEngine.
  109. JSBClassType::registerClass<ns::SomeClass>(cls);
  110. // Save the result to global variable for easily use in other places, for example class inheritance.
  111. __jsb_ns_SomeClass_proto = cls->getProto();
  112. __jsb_ns_SomeClass_class = cls;
  113. // Set a property "yyy" with the string value "helloyyy" for each object instantiated by this class.
  114. __jsb_ns_SomeClass_proto->setProperty("yyy", se::Value("helloyyy"));
  115. // Register static member variables and static member functions
  116. se::Value ctorVal;
  117. if (ns->getProperty("SomeClass", &ctorVal) && ctorVal.isObject())
  118. {
  119. ctorVal.toObject()->setProperty("static_val", se::Value(200));
  120. ctorVal.toObject()->defineFunction("static_func", _SE(js_SomeClass_static_func));
  121. }
  122. // Clear JS exceptions
  123. se::ScriptEngine::getInstance()->clearException();
  124. return true;
  125. }

How to Bind A CPP Callback Function

  1. static bool js_SomeClass_setCallback(se::State& s)
  2. {
  3. const auto& args = s.args();
  4. int argc = (int)args.size();
  5. if (argc >= 1)
  6. {
  7. ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject();
  8. se::Value jsFunc = args[0];
  9. se::Value jsTarget = argc > 1 ? args[1] : se::Value::Undefined;
  10. if (jsFunc.isNullOrUndefined())
  11. {
  12. cobj->setCallback(nullptr);
  13. }
  14. else
  15. {
  16. assert(jsFunc.isObject() && jsFunc.toObject()->isFunction());
  17. se::Object *jsTargetObj = jsTarget.isObject() ? jsTarget.toObject() : nullptr;
  18. // If the current SomeClass is a class that can be created by "new", we use "se::Object::attachObject" to associate jsFunc with jsTarget to the current object.
  19. s.thisObject()->attachObject(jsFunc.toObject());
  20. if(jsTargetObj) s.thisObject()->attachObject(jsTargetObj);
  21. // If the current SomeClass class is a singleton, or a class that always has only one instance, we can not associate it with "se::Object::attachObject".
  22. // Instead, you must use "se::Object::root", developers do not need to unroot since unroot operation will be triggered in the destruction of lambda which makes the "se::Value" jsFunc be destroyed, then "se::Object" destructor will do the unroot operation automatically.
  23. // The binding function "js_audio_AudioEngine_setFinishCallback" implements it in this way because "AudioEngine" is always a singleton.
  24. // Using "s.thisObject->attachObject(jsFunc.toObject);" for binding addCustomEventListener will cause jsFunc and jsTarget variables can't be released, which will result in memory leak.
  25. // jsFunc.toObject()->root();
  26. // jsTarget.toObject()->root();
  27. cobj->setCallback([jsFunc, jsTargetObj](int counter) {
  28. // Add the following two lines of code in CPP callback function before passing data to the JS.
  29. se::ScriptEngine::getInstance()->clearException();
  30. se::AutoHandleScope hs;
  31. se::ValueArray args;
  32. args.push_back(se::Value(counter));
  33. jsFunc.toObject()->call(args, jsTargetObj);
  34. });
  35. }
  36. return true;
  37. }
  38. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1);
  39. return false;
  40. }
  41. SE_BIND_FUNC(js_SomeClass_setCallback)

After SomeClass is registered, use it in JS like the following:

  1. var myObj = new ns.SomeClass();
  2. myObj.foo();
  3. ns.SomeClass.static_func();
  4. log("ns.SomeClass.static_val: " + ns.SomeClass.static_val);
  5. log("Old myObj.xxx:" + myObj.xxx);
  6. myObj.xxx = 1234;
  7. log("New myObj.xxx:" + myObj.xxx);
  8. log("myObj.yyy: " + myObj.yyy);
  9. var delegateObj = {
  10. onCallback: function(counter) {
  11. log("Delegate obj, onCallback: " + counter + ", this.myVar: " + this.myVar);
  12. this.setVar();
  13. },
  14. setVar: function() {
  15. this.myVar++;
  16. },
  17. myVar: 100
  18. };
  19. myObj.setCallback(delegateObj.onCallback, delegateObj);
  20. setTimeout(function(){
  21. myObj.setCallback(null);
  22. }, 6000); // Clear callback after 6 seconds.

There will be some logs outputted in console:

  1. SomeClass::foo
  2. SomeClass::static_func
  3. ns.SomeClass.static_val: 200
  4. Old myObj.xxx:0
  5. New myObj.xxx:1234
  6. myObj.yyy: helloyyy
  7. setCallback(cb)
  8. Delegate obj, onCallback: 1, this.myVar: 100
  9. Delegate obj, onCallback: 2, this.myVar: 101
  10. Delegate obj, onCallback: 3, this.myVar: 102
  11. Delegate obj, onCallback: 4, this.myVar: 103
  12. Delegate obj, onCallback: 5, this.myVar: 104
  13. Delegate obj, onCallback: 6, this.myVar: 105
  14. setCallback(nullptr)

How to Use The Helper Functions in Cocos Creator Binding for Easier Native<->JS Type Conversions

The helper functions for native<->JS type conversions are located in cocos/bindings/manual/jsb_conversions.h, it includes:

Convert se::Value to C++ Type

Support base types int*t/uint*_t/float/double/const char*/bool, std::string, bound types, their container types std::vector, std::array, std::map, std:: unordered_map, etc.

  1. template<typename T>
  2. bool sevalue_to_native(const se::Value &from, T *to, se::Object *ctx);
  3. template<typename T>
  4. bool sevalue_to_native(const se::Value &from, T *to);

Convert C++ Type to se::Value

  1. template<typename T>
  2. bool nativevalue_to_se(const T &from, se::Value &to, se::Object *ctx);
  3. template<typename T>
  4. bool nativevalue_to_se(const T &from, se::Value &to);

The following conversion functions before 3.6 have been deprecated and need to be replaced with the above two groups of functions

  1. bool seval_to_int32(const se::Value &v, int32_t *ret);
  2. bool seval_to_uint32(const se::Value &v, uint32_t *ret);
  3. bool seval_to_int8(const se::Value &v, int8_t *ret);
  4. bool seval_to_uint8(const se::Value &v, uint8_t *ret);
  5. bool seval_to_int16(const se::Value &v, int16_t *ret);
  6. bool seval_to_uint16(const se::Value &v, uint16_t *ret);
  7. bool seval_to_boolean(const se::Value &v, bool *ret);
  8. bool seval_to_float(const se::Value &v, float *ret);
  9. bool seval_to_double(const se::Value &v, double *ret);
  10. bool seval_to_size(const se::Value &v, size_t *ret);
  11. bool seval_to_std_string(const se::Value &v, std::string *ret);
  12. bool seval_to_Vec2(const se::Value &v, cc::Vec2 *pt);
  13. bool seval_to_Vec3(const se::Value &v, cc::Vec3 *pt);
  14. bool seval_to_Vec4(const se::Value &v, cc::Vec4 *pt);
  15. bool seval_to_Mat4(const se::Value &v, cc::Mat4 *mat);
  16. bool seval_to_Size(const se::Value &v, cc::Size *size);
  17. bool seval_to_ccvalue(const se::Value &v, cc::Value *ret);
  18. bool seval_to_ccvaluemap(const se::Value &v, cc::ValueMap *ret);
  19. bool seval_to_ccvaluemapintkey(const se::Value &v, cc::ValueMapIntKey *ret);
  20. bool seval_to_ccvaluevector(const se::Value &v, cc::ValueVector *ret);
  21. bool sevals_variadic_to_ccvaluevector(const se::ValueArray &args, cc::ValueVector *ret);
  22. bool seval_to_std_vector_string(const se::Value &v, std::vector<std::string> *ret);
  23. bool seval_to_std_vector_int(const se::Value &v, std::vector<int> *ret);
  24. bool seval_to_std_vector_uint16(const se::Value &v, std::vector<uint16_t> *ret);
  25. bool seval_to_std_vector_float(const se::Value &v, std::vector<float> *ret);
  26. bool seval_to_std_vector_Vec2(const se::Value &v, std::vector<cc::Vec2> *ret);
  27. bool seval_to_Uint8Array(const se::Value &v, uint8_t *ret);
  28. bool seval_to_uintptr_t(const se::Value &v, uintptr_t *ret);
  29. bool seval_to_std_map_string_string(const se::Value &v, std::map<std::string, std::string> *ret);
  30. bool seval_to_Data(const se::Value &v, cc::Data *ret);
  31. bool seval_to_DownloaderHints(const se::Value &v, cc::network::DownloaderHints *ret);
  32. template<typename T>
  33. bool seval_to_native_ptr(const se::Value& v, T* ret);
  34. template <typename T>
  35. typename std::enable_if<std::is_class<T>::value && !std::is_same<T, std::string>::value, T>::type
  36. seval_to_type(const se::Value &v, bool &ok);
  37. template <typename T>
  38. typename std::enable_if<std::is_integral<T>::value, T>::type
  39. seval_to_type(const se::Value &v, bool &ok);
  40. template <typename T>
  41. typename std::enable_if<std::is_enum<T>::value, T>::type
  42. seval_to_type(const se::Value &v, bool &ok);
  43. template <typename T>
  44. typename std::enable_if<std::is_floating_point<T>::value, T>::type
  45. seval_to_type(const se::Value &v, bool &ok);
  46. template <typename T>
  47. typename std::enable_if<std::is_same<T, std::string>::value, T>::type
  48. seval_to_type(const se::Value &v, bool &ok);
  49. template <typename T>
  50. typename std::enable_if<std::is_pointer<T>::value && std::is_class<typename std::remove_pointer<T>::type>::value, bool>::type
  51. seval_to_std_vector(const se::Value &v, std::vector<T> *ret);
  52. template <typename T>
  53. typename std::enable_if<!std::is_pointer<T>::value, bool>::type
  54. seval_to_std_vector(const se::Value &v, std::vector<T> *ret);
  55. template<typename T>
  56. bool seval_to_Map_string_key(const se::Value& v, cc::Map<std::string, T>* ret)

Replace with sevalue_to_native

  1. bool int8_to_seval(int8_t v, se::Value *ret);
  2. bool uint8_to_seval(uint8_t v, se::Value *ret);
  3. bool int32_to_seval(int32_t v, se::Value *ret);
  4. bool uint32_to_seval(uint32_t v, se::Value *ret);
  5. bool int16_to_seval(uint16_t v, se::Value *ret);
  6. bool uint16_to_seval(uint16_t v, se::Value *ret);
  7. bool boolean_to_seval(bool v, se::Value *ret);
  8. bool float_to_seval(float v, se::Value *ret);
  9. bool double_to_seval(double v, se::Value *ret);
  10. bool long_to_seval(long v, se::Value *ret);
  11. bool ulong_to_seval(unsigned long v, se::Value *ret);
  12. bool longlong_to_seval(long long v, se::Value *ret);
  13. bool uintptr_t_to_seval(uintptr_t v, se::Value *ret);
  14. bool size_to_seval(size_t v, se::Value *ret);
  15. bool std_string_to_seval(const std::string &v, se::Value *ret);
  16. bool Vec2_to_seval(const cc::Vec2 &v, se::Value *ret);
  17. bool Vec3_to_seval(const cc::Vec3 &v, se::Value *ret);
  18. bool Vec4_to_seval(const cc::Vec4 &v, se::Value *ret);
  19. bool Mat4_to_seval(const cc::Mat4 &v, se::Value *ret);
  20. bool Size_to_seval(const cc::Size &v, se::Value *ret);
  21. bool Rect_to_seval(const cc::Rect &v, se::Value *ret);
  22. bool ccvalue_to_seval(const cc::Value &v, se::Value *ret);
  23. bool ccvaluemap_to_seval(const cc::ValueMap &v, se::Value *ret);
  24. bool ccvaluemapintkey_to_seval(const cc::ValueMapIntKey &v, se::Value *ret);
  25. bool ccvaluevector_to_seval(const cc::ValueVector &v, se::Value *ret);
  26. bool std_vector_string_to_seval(const std::vector<std::string> &v, se::Value *ret);
  27. bool std_vector_int_to_seval(const std::vector<int> &v, se::Value *ret);
  28. bool std_vector_uint16_to_seval(const std::vector<uint16_t> &v, se::Value *ret);
  29. bool std_vector_float_to_seval(const std::vector<float> &v, se::Value *ret);
  30. bool std_map_string_string_to_seval(const std::map<std::string, std::string> &v, se::Value *ret);
  31. bool ManifestAsset_to_seval(const cc::extension::ManifestAsset &v, se::Value *ret);
  32. bool Data_to_seval(const cc::Data &v, se::Value *ret);
  33. bool DownloadTask_to_seval(const cc::network::DownloadTask &v, se::Value *ret);
  34. template <typename T>
  35. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
  36. native_ptr_to_seval(T *v_c, se::Value *ret, bool *isReturnCachedValue = nullptr);
  37. template <typename T>
  38. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value && !std::is_pointer<T>::value, bool>::type
  39. native_ptr_to_seval(T &v_ref, se::Value *ret, bool *isReturnCachedValue = nullptr);
  40. template <typename T>
  41. bool native_ptr_to_rooted_seval(
  42. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, T>::type *v,
  43. se::Value *ret, bool *isReturnCachedValue = nullptr);
  44. template <typename T>
  45. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
  46. native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr);
  47. template <typename T>
  48. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, bool>::type
  49. native_ptr_to_seval(T &v_ref, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr);
  50. template <typename T>
  51. bool native_ptr_to_rooted_seval(
  52. typename std::enable_if<!std::is_base_of<cc::Ref, T>::value, T>::type *v,
  53. se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr);
  54. template <typename T>
  55. typename std::enable_if<std::is_base_of<cc::Ref, T>::value, bool>::type
  56. native_ptr_to_seval(T *vp, se::Value *ret, bool *isReturnCachedValue = nullptr);
  57. template <typename T>
  58. typename std::enable_if<std::is_base_of<cc::Ref, T>::value, bool>::type
  59. native_ptr_to_seval(T *vp, se::Class *cls, se::Value *ret, bool *isReturnCachedValue = nullptr);
  60. template <typename T>
  61. bool std_vector_to_seval(const std::vector<T> &v, se::Value *ret);
  62. template <typename T>
  63. bool seval_to_reference(const se::Value &v, T **ret);

Replace with nativelue_to_se

Auxiliary conversion functions are not part of the abstraction layer (Script Engine Wrapper), they belong to the Cocos Creator binding layer and are encapsulated to facilitate more convenient conversion in the binding code. Each conversion function returns the type bool indicating whether the conversion was successful or not. Developers need to check the return value after calling these interfaces.

The specific usage is directly known according to interface names. The first parameter in the interface is input, and the second parameter is the output parameter. The usage is as follows:

  1. se::Value v;
  2. bool ok = nativevalue_to_se(100, v); // The second parameter is the output parameter, passing in the address of the output parameter
  1. int32_t v;
  2. bool ok = sevalue_to_native(args[0], &v); // The second parameter is the output parameter, passing in the address of the output parameter

More on manual binding can be found in the Using JSB Manual Binding documentation.

Automatic Binding

Configure Module .ini Files

For more specific, please refer to the engine directory tools/tojs/cocos.ini file.

Understand The Meaning of Each Field in The .ini file

  1. # Module name
  2. [cocos]
  3. # The prefix for callback functions and the binding file name.
  4. prefix = engine
  5. # The namespace of the binding class attaches to.
  6. target_namespace = jsb
  7. # Automatic binding tools is based on the Android NDK. The android_headers field configures the search path of Android header file.
  8. android_headers =
  9. # Configure building parameters for Android.
  10. android_flags = -target armv7-none-linux-androideabi -D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS -DANDROID -D__ANDROID_API__=14 -gcc-toolchain %(gcc_toolchain_dir)s --sysroot=%(androidndkdir)s/platforms/android-14/arch-arm -idirafter %(androidndkdir)s/sources/android/support/include -idirafter %(androidndkdir)s/sysroot/usr/include -idirafter %(androidndkdir)s/sysroot/usr/include/arm-linux-androideabi -idirafter %(clangllvmdir)s/lib64/clang/5.0/include -I%(androidndkdir)s/sources/cxx-stl/llvm-libc++/include
  11. # Configure the search path for clang header file.
  12. clang_headers =
  13. # Configure building parameters for clang
  14. clang_flags = -nostdinc -x c++ -std=c++17 -fsigned-char -mfloat-abi=soft -U__SSE__
  15. # Configure the search path for engine header file
  16. cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/sources
  17. # Configure building parameters for engine
  18. cocos_flags = -DANDROID -DCC_PLATFORM=3 -DCC_PLATFORM_MAC_IOS=1 -DCC_PLATFORM_MAC_OSX=4 -DCC_PLATFORM_WINDOWS=2 -DCC_PLATFORM_ANDROID=3
  19. # Configure extra building parameters
  20. extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
  21. # Which header files needed to be parsed
  22. headers = %(cocosdir)s/cocos/platform/FileUtils.h %(cocosdir)s/cocos/platform/CanvasRenderingContext2D.h %(cocosdir)s/cocos/platform/Device.h %(cocosdir)s/cocos/platform/SAXParser.h
  23. # Rename the header file in the generated binding code
  24. replace_headers =
  25. # Which classes need to be bound, you can use regular expressions, separated by space.
  26. classes = FileUtils$ SAXParser CanvasRenderingContext2D CanvasGradient Device DownloaderHints
  27. # Which classes need to be extended at the JS level, separated by spaces.
  28. classes_need_extend =
  29. # Which classes need to bind properties, separated by commas
  30. field =
  31. # Which classes need to be skipped, separated by commas
  32. skip = FileUtils::[getFileData setFilenameLookupDictionary destroyInstance getFullPathCache getContents listFilesRecursively],
  33. SAXParser::[(?!(init))],
  34. Device::[getDeviceMotionValue],
  35. CanvasRenderingContext2D::[setCanvasBufferUpdatedCallback set_.+ fillText strokeText fillRect measureText],
  36. Data::[takeBuffer getBytes fastSet copy],
  37. Value::[asValueVector asValueMap asIntKeyMap]
  38. # Which classes need to define getters and setters, separated by commas
  39. getter_setter = CanvasRenderingContext2D::[width//setWidth height//setHeight fillStyle//setFillStyle font//setFont globalCompositeOperation//setGlobalCompositeOperation lineCap//setLineCap lineJoin//setLineJoin lineWidth//setLineWidth strokeStyle//setStrokeStyle textAlign//setTextAlign textBaseline//setTextBaseline]
  40. # Which functions need to be renamed, separated by commas
  41. rename_functions = FileUtils::[loadFilenameLookupDictionaryFromFile=loadFilenameLookup]
  42. # Which classes need to be renamed, separated by commas
  43. rename_classes = SAXParser::PlistParser
  44. # Which classes do not have parents in JS
  45. classes_have_no_parents = SAXParser
  46. # Which C++ base classes need to be skipped
  47. base_classes_to_skip = Ref Clonable
  48. # Which classes are abstract classes which do not have a constructor in JS
  49. abstract_classes = SAXParser Device

Remote Debugging and Profile

By default, remote debugging and Profile are enabled in debug mode. If you need to enable them in release mode, you need to manually modify the macro switches in the file native/engine/common/CMakeLists.txt generated after building the native platform.

  1. # ...
  2. if(NOT RES_DIR)
  3. message(FATAL_ERROR "RES_DIR is not set!")
  4. endif()
  5. include(${RES_DIR}/proj/cfg.cmake)
  6. if(NOT COCOS_X_PATH)
  7. message(FATAL_ERROR "COCOS_X_PATH is not set!")
  8. endif()
  9. # ...

Change to:

  1. if(NOT RES_DIR)
  2. message(FATAL_ERROR "RES_DIR is not set!")
  3. endif()
  4. include(${RES_DIR}/proj/cfg.cmake)
  5. set(USE_V8_DEBUGGER_FORCE ON) ## 覆盖 USE_V8_DEBUGGER_FORCE 的值
  6. if(NOT COCOS_X_PATH)
  7. message(FATAL_ERROR "COCOS_X_PATH is not set!")
  8. endif()
  9. # ...

And edit file native/engine/common/Classes/Game.cpp

  1. #if CC_DEBUG
  2. _debuggerInfo.enabled = true;
  3. #else
  4. _debuggerInfo.enabled = false;
  5. #endif
  6. // Override the value above
  7. _debuggerInfo.enabled = true;

Remote Debugging V8 in Chrome

Windows/Mac

Android/iOS

Q & A

What’s The Difference between se::ScriptEngine and ScriptingCore? Why to keep ScriptingCore?

In Creator v1.7, the abstraction layer was designed as a stand-alone module that had no relation to the engine. The management of the JS engine was moved from the ScriptingCore to se::ScriptEngine class. ScriptingCore was retained in hopes of passing engine events to the abstraction layer, which acts like a adapter.

ScriptingCore only needs to be used once in AppDelegate.cpp, and all subsequent operations only require se::ScriptEngine.

  1. bool AppDelegate::applicationDidFinishLaunching()
  2. {
  3. ...
  4. ...
  5. director->setAnimationInterval(1.0 / 60);
  6. // These two lines set the ScriptingCore adapter to the engine for passing engine events, such as Node's onEnter, onExit, Action's update
  7. ScriptingCore* sc = ScriptingCore::getInstance();
  8. ScriptEngineManager::getInstance()->setScriptEngine(sc);
  9. se::ScriptEngine* se = se::ScriptEngine::getInstance();
  10. ...
  11. ...
  12. }

What’s The Difference between se::Object::root/unroot and se::Object::incRef/decRef?

root/unroot is used to control whether JS objects are controlled by GC, root means JS object should not be controlled by GC, unroot means it should be controlled by GC. For a se::Object, root and unroot can be called multiple times, se::Object‘s internal _rootCount variables is used to indicate the count of root operation. When unroot is called and _rootCount reach 0, the JS object associated with se::Object is handed over to the GC. Another situation is that if se::Object destructor is triggered and _rootCount is still greater than 0, it will force the JS object to be controlled by the GC.

incRef/decRef is used to control the life cycle of se::Object CPP object. As mentioned in the previous section, it is recommended that you use se::HandleObject to control the manual creation of unbound objects’s life cycle. So, in general, developers do not need to touch incRef/decRef.

The Association and Disassociation of Object’s Life Cycle

Use se::Object::attachObject to associate object’s life cycle.
Use se::Object::dettachObject to disassociate object’s life cycle.

objA->attachObject(objB); is similar as objA.__ nativeRefs[index] = objB in JS. Only when objA is garbage collected, objB will be possible garbage collected.
objA->dettachObject(objB); is similar as delete objA.__nativeRefs[index]; in JS. After invoking dettachObject, objB’s life cycle will not be controlled by objA.

Please DO NOT Assign A Subclass of cc::RefCounted on The Stack

Subclasses of cc::RefCounted must be allocated on the heap, via new, and then released by release. In JS object’s finalize callback function, we should use release to release. If it is allocated on the stack, the reference count is likely to be 0, and then calling release in finalize callback will result delete is invoked, which causing the program to crash. So in order to prevent this behavior from happening, developers can identify destructors as protected or private in the binding classes that inherit from cc::RefCounted, ensuring that this problem can be found during compilation.

Example:

  1. class CC_EX_DLL EventAssetsManagerEx : public EventCustom
  2. {
  3. public:
  4. ...
  5. ...
  6. private:
  7. virtual ~EventAssetsManagerEx() {}
  8. ...
  9. ...
  10. };
  11. EventAssetsManagerEx event(...); // Compilation ERROR
  12. dispatcher->dispatchEvent(&event);
  13. // Must modify to:
  14. EventAssetsManagerEx* event = new EventAssetsManagerEx(...);
  15. dispatcher->dispatchEvent(event);
  16. event->release();

How to Observe JS Exception?

In AppDelegate.cpp, using se::ScriptEngine::getInstance()->setExceptionCallback(...) to set the callback of JS exception.

  1. bool AppDelegate::applicationDidFinishLaunching()
  2. {
  3. ...
  4. ...
  5. se::ScriptEngine* se = se::ScriptEngine::getInstance();
  6. se->setExceptionCallback([](const char* location, const char* message, const char* stack){
  7. // Send exception information to server like Tencent Bugly.
  8. // ...
  9. // ...
  10. });
  11. jsb_register_all_modules();
  12. ...
  13. ...
  14. return true;
  15. }