Tutorial: JSB 2.0

This document is based on v2.x. It may change slightly on Cocos Creator 3.0 and will be updated as soon as possible.

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 revevant 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: Wrap a JS function that can be used for global functions, class member functions or class static functions
  • 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 by using cc.Class.extend.
  • SE_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

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, string, boolean, null, undefined, so se::Value uses an union to include object, number, string, boolean these 4 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. };
  12. ...
  13. ...
  14. private:
  15. union {
  16. bool _boolean;
  17. double _number;
  18. std::string* _string;
  19. Object* _object;
  20. } _u;
  21. Type _type;
  22. ...
  23. ...
  24. };
  25. }

If a 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 sp = new cc.Sprite("a.png");, we create a se::Object in the constructor callback and leave it in a global map (NativePtrToObjectMap), this map is used to query the cocos2d::Sprite* to get the corresponding JS object se::Object*.

  1. static bool js_cocos2d_Sprite_finalize(se::State& s)
  2. {
  3. CCLOG("jsbindings: finalizing JS object %p (cocos2d::Sprite)", s.nativeThisObject());
  4. cocos2d::Sprite* cobj = (cocos2d::Sprite*)s.nativeThisObject();
  5. if (cobj->getReferenceCount() == 1)
  6. cobj->autorelease();
  7. else
  8. cobj->release();
  9. return true;
  10. }
  11. SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize)
  12. static bool js_cocos2dx_Sprite_constructor(se::State& s)
  13. {
  14. cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj will be released in the finalize callback
  15. s.thisObject()->setPrivateData(cobj); // setPrivateData will make a mapping between se::Object* and cobj
  16. return true;
  17. }
  18. SE_BIND_CTOR(js_cocos2dx_Sprite_constructor, __jsb_cocos2d_Sprite_class, js_cocos2d_Sprite_finalize)

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.

It is precisely because the se::Object holds a weak reference to a JS object so that controlling the life of the CPP object by JS object can be achieved. In the above code, when the JS object is released, it will trigger the finalize callback, developers only need to release the corresponding CPP object in js_cocos2d_Sprite_finalize, the release of se::Object has been included in the SE_BIND_FINALIZE_FUNC macro by automatic processing, developers do not have to manage the release of se::Object in JS Object Control CPP Object mode, but in CPP Object Control JS Object mode, developers have the responsibility to manage the release of se::Object. I will give an example in the next section.

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 CPP object is not a subclass of cocos2d :: Ref, CPP 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 CPP object is released, you need 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
  11. // the same address.
  12. se::NativePtrToObjectMap::erase(iter);
  13. }
  14. else
  15. {
  16. return;
  17. }
  18. auto cleanup = [seObj](){
  19. auto se = se::ScriptEngine::getInstance();
  20. if (!se->isValid() || se->isInCleanup())
  21. return;
  22. se::AutoHandleScope hs;
  23. se->clearException();
  24. // The mapping of native object & se::Object was cleared in above code.
  25. // The private data (native object) may be a different object associated with other se::Object.
  26. // Therefore, don't clear the mapping again.
  27. seObj->clearPrivateData(false);
  28. seObj->unroot();
  29. seObj->decRef();
  30. };
  31. if (!se::ScriptEngine::getInstance()->isGarbageCollecting())
  32. {
  33. cleanup();
  34. }
  35. else
  36. {
  37. CleanupTask::pushTaskToAutoReleasePool(cleanup);
  38. }
  39. });

se::Object Types

  • Native Binding Object

    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 cocos2d-x, the abstraction layer is a completely separate module which does not rely on the autorelease mechanism in cocos2d-x. 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

se::HandleObject

se::HandleObject is the recommended helper class for managing the objects created manually.

  • 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 immediatelly to prevent the object being garabge 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 JS controls of CPP mode, the release of the bound object will be automatically handled by the abstraction layer. In the CPP controls JS mode, the previous chapter has already described.

  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, we could create an object by var xxx = new SomeClass (); in the JS 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 JS function could be accessed by SomeClass.foo() rather than the method of var obj = new SomeClass(); obj.foo(), 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 Cocos2D-X?

No.

This abstraction layer was originally designed as a stand-alone module which is completely independent of Cocos2D-X engine. Developers can copy the abstraction layer code in cocos/scripting/js-bindings/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 easiler demenstration.
  2. globalObj->setProperty("foo", se::Value(100)); // Set a property called `foo` with a value of 100 to the global object.

Then, you can use the foo global variable in JS directly.

  1. cc.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 easiler demenstration.
  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 easiler demenstration.
  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 Cocos2D-X 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 inheritence.
  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. // 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.
  18. s.thisObject()->attachObject(jsFunc.toObject());
  19. s.thisObject()->attachObject(jsTarget.toObject());
  20. // 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".
  21. // 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.
  22. // The binding function "js_cocos2dx_EventDispatcher_addCustomEventListener" implements it in this way because "EventDispatcher" is always a singleton.
  23. // Using "s.thisObject->attachObject(jsFunc.toObject);" for binding addCustomEventListener will cause jsFunc and jsTarget varibales can't be released, which will result in memory leak.
  24. // jsFunc.toObject()->root();
  25. // jsTarget.toObject()->root();
  26. cobj->setCallback([jsFunc, jsTarget](int counter) {
  27. // Add the following two lines of code in CPP callback function before passing data to the JS.
  28. se::ScriptEngine::getInstance()->clearException();
  29. se::AutoHandleScope hs;
  30. se::ValueArray args;
  31. args.push_back(se::Value(counter));
  32. se::Object* target = jsTarget.isObject() ? jsTarget.toObject() : nullptr;
  33. jsFunc.toObject()->call(args, target);
  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, you can use it in JS like the following:

  1. var myObj = new ns.SomeClass();
  2. myObj.foo();
  3. ns.SomeClass.static_func();
  4. cc.log("ns.SomeClass.static_val: " + ns.SomeClass.static_val);
  5. cc.log("Old myObj.xxx:" + myObj.xxx);
  6. myObj.xxx = 1234;
  7. cc.log("New myObj.xxx:" + myObj.xxx);
  8. cc.log("myObj.yyy: " + myObj.yyy);
  9. var delegateObj = {
  10. onCallback: function(counter) {
  11. cc.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 outputed 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 Cocos2D-X Binding for Easiler Native<->JS Type Conversions

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

Convert se::Value to CPP Type

  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_long(const se::Value& v, long* ret);
  11. bool seval_to_ulong(const se::Value& v, unsigned long* ret);
  12. bool seval_to_longlong(const se::Value& v, long long* ret);
  13. bool seval_to_ssize(const se::Value& v, ssize_t* ret);
  14. bool seval_to_std_string(const se::Value& v, std::string* ret);
  15. bool seval_to_Vec2(const se::Value& v, cocos2d::Vec2* pt);
  16. bool seval_to_Vec3(const se::Value& v, cocos2d::Vec3* pt);
  17. bool seval_to_Vec4(const se::Value& v, cocos2d::Vec4* pt);
  18. bool seval_to_Mat4(const se::Value& v, cocos2d::Mat4* mat);
  19. bool seval_to_Size(const se::Value& v, cocos2d::Size* size);
  20. bool seval_to_Rect(const se::Value& v, cocos2d::Rect* rect);
  21. bool seval_to_Color3B(const se::Value& v, cocos2d::Color3B* color);
  22. bool seval_to_Color4B(const se::Value& v, cocos2d::Color4B* color);
  23. bool seval_to_Color4F(const se::Value& v, cocos2d::Color4F* color);
  24. bool seval_to_ccvalue(const se::Value& v, cocos2d::Value* ret);
  25. bool seval_to_ccvaluemap(const se::Value& v, cocos2d::ValueMap* ret);
  26. bool seval_to_ccvaluemapintkey(const se::Value& v, cocos2d::ValueMapIntKey* ret);
  27. bool seval_to_ccvaluevector(const se::Value& v, cocos2d::ValueVector* ret);
  28. bool sevals_variadic_to_ccvaluevector(const se::ValueArray& args, cocos2d::ValueVector* ret);
  29. bool seval_to_blendfunc(const se::Value& v, cocos2d::BlendFunc* ret);
  30. bool seval_to_std_vector_string(const se::Value& v, std::vector<std::string>* ret);
  31. bool seval_to_std_vector_int(const se::Value& v, std::vector<int>* ret);
  32. bool seval_to_std_vector_float(const se::Value& v, std::vector<float>* ret);
  33. bool seval_to_std_vector_Vec2(const se::Value& v, std::vector<cocos2d::Vec2>* ret);
  34. bool seval_to_std_vector_Touch(const se::Value& v, std::vector<cocos2d::Touch*>* ret);
  35. bool seval_to_std_map_string_string(const se::Value& v, std::map<std::string, std::string>* ret);
  36. bool seval_to_FontDefinition(const se::Value& v, cocos2d::FontDefinition* ret);
  37. bool seval_to_Acceleration(const se::Value& v, cocos2d::Acceleration* ret);
  38. bool seval_to_Quaternion(const se::Value& v, cocos2d::Quaternion* ret);
  39. bool seval_to_AffineTransform(const se::Value& v, cocos2d::AffineTransform* ret);
  40. //bool seval_to_Viewport(const se::Value& v, cocos2d::experimental::Viewport* ret);
  41. bool seval_to_Data(const se::Value& v, cocos2d::Data* ret);
  42. bool seval_to_DownloaderHints(const se::Value& v, cocos2d::network::DownloaderHints* ret);
  43. bool seval_to_TTFConfig(const se::Value& v, cocos2d::TTFConfig* ret);
  44. //box2d seval to native convertion
  45. bool seval_to_b2Vec2(const se::Value& v, b2Vec2* ret);
  46. bool seval_to_b2AABB(const se::Value& v, b2AABB* ret);
  47. template<typename T>
  48. bool seval_to_native_ptr(const se::Value& v, T* ret);
  49. template<typename T>
  50. bool seval_to_Vector(const se::Value& v, cocos2d::Vector<T>* ret);
  51. template<typename T>
  52. bool seval_to_Map_string_key(const se::Value& v, cocos2d::Map<std::string, T>* ret)

Convert C++ Type to se::Value

  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 ssize_to_seval(ssize_t v, se::Value* ret);
  14. bool std_string_to_seval(const std::string& v, se::Value* ret);
  15. bool Vec2_to_seval(const cocos2d::Vec2& v, se::Value* ret);
  16. bool Vec3_to_seval(const cocos2d::Vec3& v, se::Value* ret);
  17. bool Vec4_to_seval(const cocos2d::Vec4& v, se::Value* ret);
  18. bool Mat4_to_seval(const cocos2d::Mat4& v, se::Value* ret);
  19. bool Size_to_seval(const cocos2d::Size& v, se::Value* ret);
  20. bool Rect_to_seval(const cocos2d::Rect& v, se::Value* ret);
  21. bool Color3B_to_seval(const cocos2d::Color3B& v, se::Value* ret);
  22. bool Color4B_to_seval(const cocos2d::Color4B& v, se::Value* ret);
  23. bool Color4F_to_seval(const cocos2d::Color4F& v, se::Value* ret);
  24. bool ccvalue_to_seval(const cocos2d::Value& v, se::Value* ret);
  25. bool ccvaluemap_to_seval(const cocos2d::ValueMap& v, se::Value* ret);
  26. bool ccvaluemapintkey_to_seval(const cocos2d::ValueMapIntKey& v, se::Value* ret);
  27. bool ccvaluevector_to_seval(const cocos2d::ValueVector& v, se::Value* ret);
  28. bool blendfunc_to_seval(const cocos2d::BlendFunc& v, se::Value* ret);
  29. bool std_vector_string_to_seval(const std::vector<std::string>& v, se::Value* ret);
  30. bool std_vector_int_to_seval(const std::vector<int>& v, se::Value* ret);
  31. bool std_vector_float_to_seval(const std::vector<float>& v, se::Value* ret);
  32. bool std_vector_Touch_to_seval(const std::vector<cocos2d::Touch*>& v, se::Value* ret);
  33. bool std_map_string_string_to_seval(const std::map<std::string, std::string>& v, se::Value* ret);
  34. bool uniform_to_seval(const cocos2d::Uniform* v, se::Value* ret);
  35. bool FontDefinition_to_seval(const cocos2d::FontDefinition& v, se::Value* ret);
  36. bool Acceleration_to_seval(const cocos2d::Acceleration* v, se::Value* ret);
  37. bool Quaternion_to_seval(const cocos2d::Quaternion& v, se::Value* ret);
  38. bool ManifestAsset_to_seval(const cocos2d::extension::ManifestAsset& v, se::Value* ret);
  39. bool AffineTransform_to_seval(const cocos2d::AffineTransform& v, se::Value* ret);
  40. bool Data_to_seval(const cocos2d::Data& v, se::Value* ret);
  41. bool DownloadTask_to_seval(const cocos2d::network::DownloadTask& v, se::Value* ret);
  42. template<typename T>
  43. bool Vector_to_seval(const cocos2d::Vector<T*>& v, se::Value* ret);
  44. template<typename T>
  45. bool Map_string_key_to_seval(const cocos2d::Map<std::string, T*>& v, se::Value* ret);
  46. template<typename T>
  47. bool native_ptr_to_seval(typename std::enable_if<!std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr);
  48. template<typename T>
  49. bool native_ptr_to_seval(typename std::enable_if<!std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr)
  50. template<typename T>
  51. bool native_ptr_to_seval(typename std::enable_if<std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr);
  52. template<typename T>
  53. bool native_ptr_to_seval(typename std::enable_if<std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr);
  54. template<typename T>
  55. bool native_ptr_to_rooted_seval(typename std::enable_if<!std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Value* ret, bool* isReturnCachedValue = nullptr);
  56. template<typename T>
  57. bool native_ptr_to_rooted_seval(typename std::enable_if<!std::is_base_of<cocos2d::Ref,T>::value,T>::type* v, se::Class* cls, se::Value* ret, bool* isReturnCachedValue = nullptr);
  58. // Spine conversions
  59. bool speventdata_to_seval(const spEventData& v, se::Value* ret);
  60. bool spevent_to_seval(const spEvent& v, se::Value* ret);
  61. bool spbonedata_to_seval(const spBoneData& v, se::Value* ret);
  62. bool spbone_to_seval(const spBone& v, se::Value* ret);
  63. bool spskeleton_to_seval(const spSkeleton& v, se::Value* ret);
  64. bool spattachment_to_seval(const spAttachment& v, se::Value* ret);
  65. bool spslotdata_to_seval(const spSlotData& v, se::Value* ret);
  66. bool spslot_to_seval(const spSlot& v, se::Value* ret);
  67. bool sptimeline_to_seval(const spTimeline& v, se::Value* ret);
  68. bool spanimationstate_to_seval(const spAnimationState& v, se::Value* ret);
  69. bool spanimation_to_seval(const spAnimation& v, se::Value* ret);
  70. bool sptrackentry_to_seval(const spTrackEntry& v, se::Value* ret);
  71. // Box2d
  72. bool b2Vec2_to_seval(const b2Vec2& v, se::Value* ret);
  73. bool b2Manifold_to_seval(const b2Manifold* v, se::Value* ret);
  74. bool b2AABB_to_seval(const b2AABB& v, se::Value* ret);

Auxiliary conversion functions are not part of the abstraction layer (Script Engine Wrapper), they belong to the Cocos2D-X 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.

You can know the specific usage directly 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 = int32_to_seval(100, &v); // The second parameter is the output parameter, passing in the address of the output parameter
  1. int32_t v;
  2. bool ok = seval_to_int32(args[0], &v); // The second parameter is the output parameter, passing in the address of the output parameter

(IMPORTANT) Understand The Difference Between native_ptr_to_seval and native_ptr_to_rooted_seval

Developers must understand the difference to make sure these conversion functions not being misused. In that case, JS memory leaks, which is really difficult to fix, could be avoided.

  • native_ptr_to_seval is used in JS control CPP object life cycle mode. This method can be called when a se::Value needs to be obtained from a CPP object pointer at the binding code. Most subclasses in the Cocos2D-X that inherit from cocos2d::Ref take this approach to get se::Value. Please remember, when the binding object, which is controlled by the JS object’s life cycle, need to be converted to seval, use this method, otherwise consider using native_ptr_to_rooted_seval.
  • native_ptr_to_rooted_seval is used in CPP controlling JS object lifecycle mode. In general, this method is used for object bindings in third-party libraries. This method will try to find the cached se::Object according the incoming CPP object pointer, if the cached se::Objectis not exist, then it will create a rooted se::Object which isn’t controlled by Garbage Collector and will always keep alive until unroot is called. Developers need to observe the release of the CPP object, and unroot se::Object. Please refer to the section introduces spTrackEntry binding (spTrackEntry_setDisposeCallback) described above.

Automatic Binding

Configure Module .ini Files

The configuration method is the same as that in Creator v1.6. The main points to note are: In Creator v1.7 script_control_cpp field is deprecated because script_control_cpp field affects the entire module. If the module needs to bind the cocos2d::Ref subclass and non-cocos2d::Ref class, the original binding configuration in v1.6 can not meet the demand. The new field introduced in v1.7 is classes_owned_by_cpp, which indicates which classes need to be controlled by the CPP object’s life cycle.

An additional, there is a configuration field in v1.7 is persistent_classes to indicate which classes are always present during game play, such as: SpriteFrameCache, FileUtils, EventDispatcher, ActionManager, Scheduler.

Other fields are the same as v1.6.

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

Understand The Meaning of Each Field in The .ini file

  1. # Module name
  2. [cocos2d-x]
  3. # The prefix for callback functions and the binding file name.
  4. prefix = cocos2dx
  5. # The namspace of the binding class attaches to.
  6. target_namespace = cc
  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 = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/include
  9. # Configure building parameters for Android.
  10. android_flags = -D_SIZE_T_DEFINED_
  11. # Configure the search path for clang header file.
  12. clang_headers = -I%(clangllvmdir)s/%(clang_include)s
  13. # Configure building parameters for clang
  14. clang_flags = -nostdinc -x c++ -std=c++11 -U __SSE__
  15. # Configure the search path for Cocos2D-X 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 Cocos2D-X
  18. cocos_flags = -DANDROID
  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/cocos2d.h %(cocosdir)s/cocos/scripting/js-bindings/manual/BaseJSAction.h
  23. # Rename the header file in the generated binding code
  24. replace_headers=CCProtectedNode.h::2d/CCProtectedNode.h,CCAsyncTaskPool.h::base/CCAsyncTaskPool.h
  25. # Which classes need to be bound, you can use regular expressions, separated by space.
  26. classes =
  27. # Which classes which use cc.Class.extend to inherit, separated by space.
  28. classes_need_extend =
  29. # Which classes need to bind properties, separated by commas
  30. field = Acceleration::[x y z timestamp]
  31. # Which classes need to be skipped, separated by commas
  32. skip = AtlasNode::[getTextureAtlas],
  33. ParticleBatchNode::[getTextureAtlas],
  34. # Which functions need to be renamed, separated by commas
  35. rename_functions = ComponentContainer::[get=getComponent],
  36. LayerColor::[initWithColor=init],
  37. # Which classes need to be renamed, separated by commas
  38. rename_classes = SimpleAudioEngine::AudioEngine,
  39. SAXParser::PlistParser,
  40. # Which classes do not have parents in JS
  41. classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo Application GLViewProtocol SAXParser Configuration
  42. # Which C++ base classes need to be skipped
  43. base_classes_to_skip = Ref Clonable
  44. # Which classes are abstract classes which do not have a constructor in JS
  45. abstract_classes = Director SpriteFrameCache Set SimpleAudioEngine
  46. # Which classes are singleton or always keep alive until game exits
  47. persistent_classes = SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler
  48. # Which classes use `CPP object controls JS object's life cycle`, the unconfigured classes will use `JS controls CPP object's life cycle`.
  49. classes_owned_by_cpp =

Remote Debugging and Profile

The remote debugging and profile are valid in debug mode, if you need to enable in release mode, you need to manually modify the macro in cocos/scripting/js-bindings/jswrapper/config.hpp.

  1. #if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
  2. #define SE_ENABLE_INSPECTOR 1
  3. #define SE_DEBUG 2
  4. #else
  5. #define SE_ENABLE_INSPECTOR 0
  6. #define SE_DEBUG 0
  7. #endif

Change to:

  1. #if 1 // Change to 1 to force enable remote debugging
  2. #define SE_ENABLE_INSPECTOR 1
  3. #define SE_DEBUG 2
  4. #else
  5. #define SE_ENABLE_INSPECTOR 0
  6. #define SE_DEBUG 0
  7. #endif

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.

What’s The Difference of Object Life Management between The Subclass of cocos2d::Ref and non-cocos2d::Ref class?

The binding of cocos2d::Ref subclass in the current engine adopts JS object controls the life cycle of CPP object. The advantage of doing so is to solve the retain/release problem that has been criticized in the JS layer.

Non-cocos2d::Ref class takes the way of CPP object controls the life of a JS object. This method requires that after CPP object is destroyed, it needs to notify the binding layer to call the clearPrivateData, unroot, and decRef methods corresponding to se::Object. JS code must be careful operation of the object, when there may be illegal object logic, use cc.sys.isObjectValid to determine whether the CPP object is released.

NOTE of Binding The Finalize Function for cocos2d::Ref Subclass

Calling any JS engine’s API in a finalize callback can lead to a crash. Because the current engine is in garbage collection process, which can not be interrupted to deal with other operations.

Finalize callback is to tell the CPP layer to release the memory of the corresponding CPP object, we should not call any JS engine API in the CPP object’s destructor either.

But if that must be called, how should we deal with?

In Cocos2D-X binding, if the native object’s reference count is 1, we do not use the release, but using autorelease to delay CPP object’s destructor to be executed at the end of frame. For instance:

  1. static bool js_cocos2d_Sprite_finalize(se::State& s)
  2. {
  3. CCLOG("jsbindings: finalizing JS object %p (cocos2d::Sprite)", s.nativeThisObject());
  4. cocos2d::Sprite* cobj = (cocos2d::Sprite*)s.nativeThisObject();
  5. if (cobj->getReferenceCount() == 1)
  6. cobj->autorelease();
  7. else
  8. cobj->release();
  9. return true;
  10. }
  11. SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize)

Please DO NOT Assign A Subclass of cocos2d::Ref on The Stack

Subclasses of cocos2d::Ref must be allocated on the heap, via new, and then released by release. In JS object’s finalize callback function, we should use autorelease or 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 cocos2d::Ref, ensuring that this problem can be found during compilation.

E.g:

  1. class CC_EX_DLL EventAssetsManagerEx : public cocos2d::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. }