Using JSB Auto Binding

This article is republished from Tencent Online Education Department Technical Blog
Author: kevinxzhang

Creator provides native.reflection.callStaticMethod method to support the interface of calling Native side (Android/iOS/Mac) directly from TypeScript side, but after much practice, we found that the performance of this interface is very low under a lot of frequent calls, especially on Android side, such as calling the interface implemented on Native side for printing logs. And it is easy to cause some native crashes, such as local reference table overflow and other problems. Throughout the implementation of Cocos native code, basically all interface methods are implemented based on the JSB approach, so this article mainly explains the JSB auto-binding logic to help you quickly implement the callStaticMethod to JSB transformation process.

Background

For those who have used Cocos Creator (or CC for convenience), native.reflection.callStaticMethod is certainly no stranger to providing the ability to call the Native side from the TypeScript side. For example, if we want to call the Native implementation of the log printing and persistence interface, we can easily do so in JavaScript as follows:

  1. import {NATIVE} from 'cc/env';
  2. if (NATIVE && sys.os == sys.OS.IOS) {
  3. msg = this.buffer_string + '\n[cclog][' + clock + '][' + tag + ']' + msg;
  4. native.reflection.callStaticMethod("ABCLogService", "log:module:level:", msg, 'cclog', level);
  5. return;
  6. } else if (NATIVE && sys.os == sys.OS.ANDROID) {
  7. msg = this.buffer_string + '\n[cclog][' + clock + '][' + tag + ']' + msg;
  8. native.reflection.callStaticMethod("com/example/test/CommonUtils", "log", "(ILjava/lang/String;Ljava/lang/String;)V", level, 'cclog', msg);
  9. return;
  10. }

It is very simple to use and can be called cross-platform in one line of code, a little look at its implementation shows that the C++ layer is implemented in the Android side by way of jni, and the iOS side is called dynamically by way of runtime. However, in order to take into account the generality and support all methods, the Android side does not have a caching mechanism for jni-related objects, which can lead to serious performance problems when a large number of calls are made in a short period of time. Previously we encountered more cases is printing log in the downloader, some application scenarios trigger a large number of download operations in a short period of time, resulting in local reference table overflow crashes, or even interface lag on low-end machines that cannot be loaded out.

Fixing this problem requires a JSB modification for log calls, along with a caching mechanism related to jni to optimize performance. jSB binding is simply the process of converting objects between the C++ and script layers, and forwarding script layer function calls to the C++ layer.

JSB binding is usually done in two ways: manual binding and automatic binding. The manual binding method can be found in the Using JSB Manual Binding documentation.

  • The advantage of manual binding is that it is flexible and customizable; the disadvantage is the necessity to write all the code yourself, especially the conversion between C++ type and TypeScript type, which can easily lead to memory leaks and some pointers or objects not being freed.
  • Auto-binding will save a lot of trouble, which directly generates the relevant code through a script in one click, and subsequently, if there are new codes or changes, simply re-execute the script once. Auto-binding is perfect for cases where it is not necessary to do strong customization and then need to finish JSB quickly. The following is a step-by-step explanation of how to implement automatic JSB binding.

Environment Configuration and Auto-Binding Demonstration

Environment Configuration

Auto-binding, to put it simply, is a matter of executing a python script to automatically generate the corresponding .cpp and .h files. First,make sure that the computer has a python runtime environment. Example of how to install it on a Mac:

  1. To install python 3.0, download the installation package from the python website:

    https://www.python.org/downloads/release/python-398/

  2. Install some of the python dependencies via pip3:

    1. sudo pip3 install pyyaml==5.4.1
    2. sudo pip3 install Cheetah3
  3. Install the NDK, which is definitely essential when it comes to C++. It is recommended to install the Android NDK r21e version, set the PYTH_profile in ~/.bash_ profile, then set PYTHON_ROOT and NDK_ROOT in ~/.bash_profile, because these two environment variables will be used directly in the python file that will be executed later.

    1. export NDK_ROOT=/Users/kevin/android-ndk-r21e
    2. export PYTHON_BIN=python3

In Windows, directly install the modules by referring to the above, and remember to configure the environment variables at the end.

Auto-Binding Demonstration

Here’s a demonstration of how the files under the cocos engine, i.e. the cocos/bindings/auto directory (shown below) are automatically generate:

JSB Auto Binding - 图1

In fact, the beginning of these file names that there are some specific rules for naming these files, so how are these files generated? First, open a terminal, cd to the tools/tojs directory, and then run ./genbindings.py.

JSB Auto Binding - 图2

After about a minute or so of running, the following message will appear, indicating that it has been successfully generated:

JSB Auto Binding - 图3

After the above steps, all the files under cocos/bindings/auto will be automatically generated, which is very convenient.

The following is an example of how the TypeScript layer prints logs by calling the Native layer log method through JSB, and how to implement the auto-binding tool to generate the corresponding auto-binding files based on the C++ code written.

Writing the C++ layer implementation

C++ is the bridge between TypeScript and Native layers. To implement JSB calls, the first step is to prepare the header files and implementation for the C++ layer, here we create a test folder in cocos directory to store the relevant files:

JSB Auto Binding - 图4

ABCJSBBridge.h, declares an abcLog function for the TypeScript layer to call the logging, and because the logging method will certainly be used in many places in the TypeScript layer, a singleton pattern is used here, providing getInstance() to get the current instance of the class.

  1. #pragma once
  2. #include <string>
  3. namespace abc
  4. {
  5. class JSBBridge
  6. {
  7. public:
  8. void abcLog(const std::string& msg);
  9. /**
  10. * Returns a shared instance of the director.
  11. * @js _getInstance
  12. */
  13. static JSBBridge* getInstance();
  14. /** @private */
  15. JSBBridge();
  16. /** @private */
  17. ~JSBBridge();
  18. bool init();
  19. };
  20. }

The following is the corresponding implementation of ABCJSBBridge.cpp:

  1. #include <cocos/base/Log.h>
  2. #include "ABCJSBBridge.h"
  3. namespace abc
  4. {
  5. // singleton stuff
  6. static JSBBridge *s_SharedJSBBridge = nullptr;
  7. JSBBridge::JSBBridge()
  8. {
  9. CC_LOG_ERROR("Construct JSBBridge %p", this);
  10. init();
  11. }
  12. JSBBridge::~JSBBridge()
  13. {
  14. CC_LOG_ERROR("Destruct JSBBridge %p", this);
  15. s_SharedJSBBridge = nullptr;
  16. }
  17. JSBBridge* JSBBridge::getInstance()
  18. {
  19. if (!s_SharedJSBBridge)
  20. {
  21. CC_LOG_ERROR("getInstance JSBBridge ");
  22. s_SharedJSBBridge = new (std::nothrow) JSBBridge();
  23. CCASSERT(s_SharedJSBBridge, "FATAL: Not enough memory for create JSBBridge");
  24. }
  25. return s_SharedJSBBridge;
  26. }
  27. bool JSBBridge::init(void)
  28. {
  29. CC_LOG_ERROR("init JSBBridge ");
  30. return true;
  31. }
  32. void JSBBridge::abcLog(const std::string& msg)
  33. {
  34. CC_LOG_ERROR("%s", msg.c_str());
  35. }
  36. }

JSB Configuration Scripting

Find the genbindings.py script in the tools/tojs directory, copy it and rename it to genbindings_test.py, then modify the genbindings_test.py module configuration to keep only the cocos2dx_test module.

JSB Auto Binding - 图5

The next step is to add a custom configuration file cocos2dx_test.ini to the tools/tojs directory, which is actually similar to the other .ini files under tools/tojs, mainly to let the auto-binding tool know which APIs to bind and in what way. Refer directly to Cocos’ existing .ini file to write this, here is the contents of cocos2dx_test.ini:

  1. [cocos2dx_test]
  2. # the prefix to be added to the generated functions. You might or might not use this in your own
  3. # templates
  4. prefix = cocos2dx_test
  5. # create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
  6. # all classes will be embedded in that namespace
  7. target_namespace = abc
  8. macro_judgement =
  9. android_headers =
  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. clang_headers =
  12. clang_flags = -nostdinc -x c++ -std=c++17 -fsigned-char -mfloat-abi=soft -U__SSE__
  13. cocos_headers = -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external/sources
  14. cocos_flags = -DANDROID -DCC_PLATFORM=3 -DCC_PLATFORM_MAC_IOS=1 -DCC_PLATFORM_MAC_OSX=4 -DCC_PLATFORM_WINDOWS=2 -DCC_PLATFORM_ANDROID=3
  15. cxxgenerator_headers =
  16. # extra arguments for clang
  17. 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
  18. # what headers to parse
  19. headers = %(cocosdir)s/cocos/test/ABCJSBBridge.h
  20. # cpp_headers = network/js_network_manual.h
  21. # what classes to produce code for. You can use regular expressions here. When testing the regular
  22. # expression, it will be enclosed in "^$", like this: "^Menu*$".
  23. classes = JSBBridge
  24. # what should we skip? in the format ClassName::[function function]
  25. # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
  26. # regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
  27. # add a single "*" as functions. See bellow for several examples. A special class name is "*", which
  28. # will apply to all class names. This is a convenience wildcard to be able to skip similar named
  29. # functions from all classes.
  30. skip = JSBBridge::[init]
  31. rename_functions =
  32. rename_classes =
  33. # for all class names, should we remove something when registering in the target VM?
  34. remove_prefix =
  35. # classes for which there will be no "parent" lookup
  36. classes_have_no_parents = JSBBridge
  37. # base classes which will be skipped when their sub-classes found them.
  38. base_classes_to_skip = Clonable
  39. # classes that create no constructor
  40. # Set is special and we will use a hand-written constructor
  41. abstract_classes = JSBBridge

In fact, the annotations inside are also very detailed, and here are a few of the main properties and their meanings:

PropertyDescription
prefixDefine the name of the function inside the generated binding file. The combination of function name is js + prefix + the function name in the header file. For example, if we define JSBBridge_ abcLog in the header file and set the prefix to cocos2dx test, the function name in the final binding file will be js_cocos2dx_test_JSBBridge_abcLog.
target_namespaceThe target namespace in the script, e.g.: cc, spine, etc.
headersList of headers to be bound, separated by spaces, headers will be scanned recursively.
cpp_headersList of header files that need to be included in the binding code but do not need to be scanned by the binding tool.
classesList of class names to be bound, separated by spaces.
abstract_classesWhen configured as an abstract class, its constructors will not be bound, separated by spaces.

Once the above configuration is done, cd to the tools/tojs directory and run ./genbindings_test.py to automatically generate the bindings file. Notice the two bindings under cocos/bindings/auto:

JSB Auto Binding - 图6

Open the generated jsb_cocos2dx_test_auto.cpp:

  1. #include "cocos/bindings/auto/jsb_cocos2dx_test_auto.h"
  2. #include "cocos/bindings/manual/jsb_conversions.h"
  3. #include "cocos/bindings/manual/jsb_global.h"
  4. #include "test/ABCJSBBridge.h"
  5. #ifndef JSB_ALLOC
  6. #define JSB_ALLOC(kls, ...) new (std::nothrow) kls(__VA_ARGS__)
  7. #endif
  8. #ifndef JSB_FREE
  9. #define JSB_FREE(ptr) delete ptr
  10. #endif
  11. se::Object* __jsb_abc_JSBBridge_proto = nullptr;
  12. se::Class* __jsb_abc_JSBBridge_class = nullptr;
  13. static bool js_cocos2dx_test_JSBBridge_abcLog(se::State& s) // NOLINT(readability-identifier-naming)
  14. {
  15. auto* cobj = SE_THIS_OBJECT<abc::JSBBridge>(s);
  16. SE_PRECONDITION2(cobj, false, "js_cocos2dx_test_JSBBridge_abcLog : Invalid Native Object");
  17. const auto& args = s.args();
  18. size_t argc = args.size();
  19. CC_UNUSED bool ok = true;
  20. if (argc == 1) {
  21. HolderType<std::string, true> arg0 = {};
  22. ok &= sevalue_to_native(args[0], &arg0, s.thisObject());
  23. SE_PRECONDITION2(ok, false, "js_cocos2dx_test_JSBBridge_abcLog : Error processing arguments");
  24. cobj->abcLog(arg0.value());
  25. return true;
  26. }
  27. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
  28. return false;
  29. }
  30. SE_BIND_FUNC(js_cocos2dx_test_JSBBridge_abcLog)
  31. static bool js_cocos2dx_test_JSBBridge_getInstance(se::State& s) // NOLINT(readability-identifier-naming)
  32. {
  33. const auto& args = s.args();
  34. size_t argc = args.size();
  35. CC_UNUSED bool ok = true;
  36. if (argc == 0) {
  37. abc::JSBBridge* result = abc::JSBBridge::getInstance();
  38. ok &= nativevalue_to_se(result, s.rval(), nullptr /*ctx*/);
  39. SE_PRECONDITION2(ok, false, "js_cocos2dx_test_JSBBridge_getInstance : Error processing arguments");
  40. SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval());
  41. return true;
  42. }
  43. SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
  44. return false;
  45. }
  46. SE_BIND_FUNC(js_cocos2dx_test_JSBBridge_getInstance)
  47. bool js_register_cocos2dx_test_JSBBridge(se::Object* obj) // NOLINT(readability-identifier-naming)
  48. {
  49. auto* cls = se::Class::create("JSBBridge", obj, nullptr, nullptr);
  50. cls->defineFunction("abcLog", _SE(js_cocos2dx_test_JSBBridge_abcLog));
  51. cls->defineStaticFunction("getInstance", _SE(js_cocos2dx_test_JSBBridge_getInstance));
  52. cls->install();
  53. JSBClassType::registerClass<abc::JSBBridge>(cls);
  54. __jsb_abc_JSBBridge_proto = cls->getProto();
  55. __jsb_abc_JSBBridge_class = cls;
  56. se::ScriptEngine::getInstance()->clearException();
  57. return true;
  58. }
  59. bool register_all_cocos2dx_test(se::Object* obj)
  60. {
  61. // Get the ns
  62. se::Value nsVal;
  63. if (!obj->getProperty("abc", &nsVal))
  64. {
  65. se::HandleObject jsobj(se::Object::createPlainObject());
  66. nsVal.setObject(jsobj);
  67. obj->setProperty("abc", nsVal);
  68. }
  69. se::Object* ns = nsVal.toObject();
  70. js_register_cocos2dx_test_JSBBridge(ns);
  71. return true;
  72. }

Doesn’t it look familiar? It’s exactly the same as Cocos’ existing .cpp files, even including the registration functions and class definitions that are all automatically generated.

Cocos Compilation Configuration

Although we have generated the bindings after the above step, the TypeScript layer can’t be used directly because we still need to configure the generated bindings into the CMakeLists.txt file to be compiled with other C++ files, which is the last part of the CMakeLists.txt compilation configuration.

  1. Open the CMakeLists.txt file and add the initial ABCJSBBridge.h and ABCJSBBridge.cpp to it, as well as the jsb_cocos2dx_test_auto.h and jsb_cocos2dx_test_auto.cpp files generated by the automatic bindings:

    JSB Auto Binding - 图7

  2. Open cocos/bindings/manual/jsb_module_register.cpp and add the registration code for the cocos2dx_test module:

    JSB Auto Binding - 图8

After the above configuration, call it directly from the TypeScript layer like this:

  1. import { _decorator, Component, Node } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('Test')
  4. export class Test extends Component {
  5. start () {
  6. // @ts-ignore
  7. abc.JSBBridge.getInstance().abcLog("JSB binding test success")
  8. }
  9. }

Restrictions on Auto-Binding

Auto-binding relies on the Bindings Generator tool. The Bindings Generator tool can Bind public methods and public properties of C++ classes to the scripting layer. The automatic binding tool, although very powerful, has a few limitations:

  1. It can only generate bindings for classes, not structs, independent functions, etc.
  2. It is not possible to generate Delegate type APIs, because objects in scripts cannot inherit from the Delegate class in C++ and override the Delegate functions in it.
  3. The child class overrides the API of the parent class while overriding this API.
  4. Part of the API implementation is not fully reflected in its API definition.
  5. The API is actively called by C++ at runtime.

NOTICE: Since 3.6 the types of parameters and return values involved in auto-binding need to be bound as well, or the conversion methods sevalue_to_native/nativevalue_to_se need to be provided, otherwise they will be saved at compile time. Before 3.5, it was reported as a runtime error.

Summary

In summary, automatic binding of JSBs only requires the developer to write the relevant C++ implementation class, a configuration file, and then execute a single command to complete the entire binding process. If there is no special customization, it is still a lot more efficient than manual binding. The actual work can be done on a case-by-case basis by first using the auto-binding feature, and then manually modifying the generated binding file to achieve half the result with twice the effort.