Native与Sendable ArkTS对象绑定
=========================

#### 场景介绍

通过napi\_wrap\_sendable将[Sendable](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-sendable) ArkTS对象与Native的C++对象绑定，后续操作时再通过napi\_unwrap\_sendable将ArkTS对象绑定的C++对象取出，并对其进行操作。

#### 使用示例

1.  接口声明、编译配置以及模块注册
    
    **接口声明**
    
    // index.d.ets
    @Sendable
    export class MyObject {
      constructor(arg: number);
      plusOne(): number;
    
      public get value();
      public set value(newVal: number);
    }
    
    **编译配置**
    
    \# the minimum version of CMake.
    cmake\_minimum\_required(VERSION 3.5.0)
    project(napi\_wrap\_sendable\_demo)
    
    set(NATIVERENDER\_ROOT\_PATH ${CMAKE\_CURRENT\_SOURCE\_DIR})
    
    if(DEFINED PACKAGE\_FIND\_FILE)
        include(${PACKAGE\_FIND\_FILE})
    endif()
    
    include\_directories(${NATIVERENDER\_ROOT\_PATH}
                        ${NATIVERENDER\_ROOT\_PATH}/include)
    
    add\_definitions("-DLOG\_DOMAIN=0x0000")
    add\_definitions("-DLOG\_TAG=\\"testTag\\"")
    
    add\_library(entry SHARED napi\_init.cpp)
    target\_link\_libraries(entry PUBLIC libace\_napi.z.so libhilog\_ndk.z.so)
    
    **模块注册**
    
    // napi\_init.cpp
    #include "napi/native\_api.h"
    #include "hilog/log.h"
    
    // 一个native类，它的实例在下面会包装在Sendable ArkTS对象中
    class MyObject {
    public:
        static napi\_value Init(napi\_env env, napi\_value exports);
        static void Destructor(napi\_env env, void \*nativeObject, void \*finalize\_hint);
    
    private:
        explicit MyObject(double value\_ = 0);
        ~MyObject();
    
        static napi\_value New(napi\_env env, napi\_callback\_info info);
        static napi\_value GetValue(napi\_env env, napi\_callback\_info info);
        static napi\_value SetValue(napi\_env env, napi\_callback\_info info);
        static napi\_value PlusOne(napi\_env env, napi\_callback\_info info);
    
        double value\_;
        napi\_env env\_;
    };
    
    static thread\_local napi\_ref g\_ref = nullptr;
    
    MyObject::MyObject(double value) : value\_(value), env\_(nullptr) {}
    
    MyObject::~MyObject() {}
    
    void MyObject::Destructor(napi\_env env, void \*nativeObject, \[\[maybe\_unused\]\] void \*finalize\_hint) {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::Destructor called");
        reinterpret\_cast<MyObject \*>(nativeObject)->~MyObject();
    }
    
    napi\_value MyObject::Init(napi\_env env, napi\_value exports) {
        napi\_value num = nullptr;
        napi\_status status = napi\_create\_double(env, 0, &num);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_create\_double fail");
            return nullptr;
        }
        napi\_property\_descriptor properties\[\] = {
            {"value", nullptr, nullptr, GetValue, SetValue, nullptr, napi\_default, nullptr},
            {"plusOne", nullptr, PlusOne, nullptr, nullptr, nullptr, napi\_default, nullptr},
        };
    
        napi\_value cons = nullptr;
        // 定义一个Sendable class MyObject
        status = napi\_define\_sendable\_class(env, "MyObject", NAPI\_AUTO\_LENGTH, New, nullptr,
                                sizeof(properties) / sizeof(properties\[0\]), properties, nullptr, &cons);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_define\_sendable\_class fail");
            return nullptr;
        }
    
        status = napi\_create\_reference(env, cons, 1, &g\_ref);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_create\_reference fail");
            return nullptr;
        }
        // 在exports对象上挂载MyObject类
        status = napi\_set\_named\_property(env, exports, "MyObject", cons);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_set\_named\_property fail");
            return nullptr;
        }
        return exports;
    }
    
    EXTERN\_C\_START
    // 模块初始化
    static napi\_value Init(napi\_env env, napi\_value exports) {
        MyObject::Init(env, exports);
        return exports;
    }
    EXTERN\_C\_END
    
    // 准备模块加载相关信息，将上述Init函数与本模块名等信息记录下来。
    static napi\_module nativeModule = {
        .nm\_version = 1,
        .nm\_flags = 0,
        .nm\_filename = nullptr,
        .nm\_register\_func = Init,
        .nm\_modname = "entry",
        .nm\_priv = nullptr,
        .reserved = {0},
    };
    
    // 加载so时，该函数会自动被调用，将上述nativeModule模块注册到系统中。
    extern "C" \_\_attribute\_\_((constructor)) void RegisterObjectWrapModule() { napi\_module\_register(&nativeModule); }
    
2.  在构造函数中绑定Sendable ArkTS与C++对象
    
    napi\_value MyObject::New(napi\_env env, napi\_callback\_info info) {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::New called");
    
        napi\_value newTarget = nullptr;
        napi\_status status = napi\_get\_new\_target(env, info, &newTarget);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_get\_new\_target fail");
            return nullptr;
        }
        if (newTarget != nullptr) {
            // 使用\`new MyObject(...)\`调用方式
            size\_t argc = 1;
            napi\_value args\[1\] = { nullptr };
            napi\_value jsThis = nullptr;
            status = napi\_get\_cb\_info(env, info, &argc, args, &jsThis, nullptr);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_get\_cb\_info fail");
                return nullptr;
            }
    
            double value = 0.0;
            napi\_valuetype valuetype = napi\_undefined;
            status = napi\_typeof(env, args\[0\], &valuetype);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_typeof fail");
                return nullptr;
            }
            if (valuetype != napi\_undefined) {
                status = napi\_get\_value\_double(env, args\[0\], &value);
                if (status != napi\_ok) {
                    napi\_throw\_error(env, nullptr, "Node-API napi\_get\_value\_double fail");
                    return nullptr;
                }
            }
    
            MyObject \*obj = new MyObject(value);
    
            obj->env\_ = env;
            // 通过napi\_wrap\_sendable将Sendable ArkTS对象jsThis与C++对象obj绑定
            status = napi\_wrap\_sendable(env, jsThis, reinterpret\_cast<void \*>(obj), MyObject::Destructor, nullptr);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_wrap\_sendable fail");
                delete obj;
                return nullptr;
            }
    
            return jsThis;
        } else {
            // 使用\`MyObject(...)\`调用方式
            size\_t argc = 1;
            napi\_value args\[1\] = { nullptr };
            status = napi\_get\_cb\_info(env, info, &argc, args, nullptr, nullptr);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_get\_cb\_info fail");
                return nullptr;
            }
    
            napi\_value cons = nullptr;
            status = napi\_get\_reference\_value(env, g\_ref, &cons);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_get\_reference\_value fail");
                return nullptr;
            }
            napi\_value instance = nullptr;
            status = napi\_new\_instance(env, cons, argc, args, &instance);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_new\_instance fail");
                return nullptr;
            }
    
            return instance;
        }
    }
    
3.  将Sendable ArkTS对象之前绑定的C++对象取出，并对其进行操作
    
    napi\_value MyObject::GetValue(napi\_env env, napi\_callback\_info info) {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::GetValue called");
    
        napi\_value jsThis = nullptr;
        napi\_status status = napi\_get\_cb\_info(env, info, nullptr, nullptr, &jsThis, nullptr);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_get\_cb\_info fail");
            return nullptr;
        }
    
        MyObject \*obj = nullptr;
        // 通过napi\_unwrap\_sendable将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap\_sendable(env, jsThis, reinterpret\_cast<void \*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap\_sendable fail");
            return nullptr;
        }
        napi\_value num = nullptr;
        status = napi\_create\_double(env, obj->value\_, &num);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_create\_double fail");
            return nullptr;
        }
    
        return num;
    }
    
    napi\_value MyObject::SetValue(napi\_env env, napi\_callback\_info info) {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::SetValue called");
    
        size\_t argc = 1;
        napi\_value value = nullptr;
        napi\_value jsThis = nullptr;
    
        napi\_status status = napi\_get\_cb\_info(env, info, &argc, &value, &jsThis, nullptr);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_get\_cb\_info fail");
            return nullptr;
        }
    
        MyObject \*obj = nullptr;
        // 通过napi\_unwrap\_sendable将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap\_sendable(env, jsThis, reinterpret\_cast<void \*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap\_sendable fail");
            return nullptr;
        }
        status = napi\_get\_value\_double(env, value, &obj->value\_);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_get\_value\_double fail");
            return nullptr;
        }
    
        return nullptr;
    }
    
    napi\_value MyObject::PlusOne(napi\_env env, napi\_callback\_info info) {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::PlusOne called");
    
        napi\_value jsThis = nullptr;
        napi\_status status = napi\_get\_cb\_info(env, info, nullptr, nullptr, &jsThis, nullptr);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_get\_cb\_info fail");
            return nullptr;
        }
    
        MyObject \*obj = nullptr;
        // 通过napi\_unwrap\_sendable将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap\_sendable(env, jsThis, reinterpret\_cast<void \*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap\_sendable fail");
            return nullptr;
        }
        obj->value\_ += 1;
        napi\_value num = nullptr;
        status = napi\_create\_double(env, obj->value\_, &num);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_create\_double fail");
            return nullptr;
        }
    
        return num;
    }
    
4.  ArkTS侧示例代码
    
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { MyObject } from 'libentry.so';
    
    try {
        let object : MyObject = new MyObject(0);
        object.value = 1023.1;
        hilog.info(0x0000, 'testTag', 'MyObject value after set: %{public}s', object.value.toString());
        hilog.info(0x0000, 'testTag', 'MyObject plusOne: %{public}s', object.plusOne().toString());
    } catch (error) {
        hilog.error(0x0000, 'testTag', 'Test Node-API error: %{public}s', error.message);
    }