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

#### 场景介绍

通过napi\_wrap将ArkTS对象与Native的C++对象绑定，后续操作时再通过napi\_unwrap将ArkTS对象绑定的C++对象取出，并对其进行操作。

#### 使用示例

1.  接口声明、编译配置以及模块注册
    
    **接口声明**
    
    // index.d.ts
    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\_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"
    
    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\_;
        napi\_ref wrapper\_;
    };
    
    MyObject::MyObject(double value) : value\_(value), env\_(nullptr), wrapper\_(nullptr) {}
    
    MyObject::~MyObject()
    {
        napi\_status status = napi\_delete\_reference(env\_, wrapper\_);
        if (status != napi\_ok) {
            OH\_LOG\_INFO(LOG\_APP, "Failed to delete reference, return code: %{public}d", status);
        }
    }
    
    void MyObject::Destructor(napi\_env env, void\* nativeObject, \[\[maybe\_unused\]\] void\* finalize\_hint)
    {
        OH\_LOG\_INFO(LOG\_APP, "MyObject::Destructor called");
        delete reinterpret\_cast<MyObject\*>(nativeObject);
    }
    
    napi\_value MyObject::Init(napi\_env env, napi\_value exports)
    {
        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;
        napi\_status status = napi\_define\_class(env, "MyObject", NAPI\_AUTO\_LENGTH, New, nullptr, 2, properties, &cons);
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_define\_class fail");
            return nullptr;
        }
    
        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
    
    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 },
    };
    
    extern "C" \_\_attribute\_\_((constructor)) void RegisterObjectWrapModule()
    {
        napi\_module\_register(&nativeModule);
    }
    
2.  在构造函数中绑定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将ArkTS对象jsThis)与C++对象obj绑定
            status = napi\_wrap(env,
                               jsThis,
                               reinterpret\_cast<void\*>(obj),
                               MyObject::Destructor,
                               nullptr,  // finalize\_hint
                               &obj->wrapper\_);
            // napi\_wrap失败时，必须手动释放已分配的内存，以防止内存泄漏
            if (status != napi\_ok) {
                delete obj;
                napi\_throw\_error(env, nullptr, "Node-API napi\_wrap fail");
                return jsThis;
            }
            // 从napi\_wrap接口的result获取napi\_ref的行为，将会为jsThis创建强引用，
            // 若开发者不需要主动管理jsThis的生命周期，可直接在napi\_wrap最后一个参数中传入nullptr，
            // 或者使用napi\_reference\_unref方法将napi\_ref转为弱引用。
            uint32\_t refCount = 0;
            napi\_reference\_unref(env, obj->wrapper\_, &refCount);
    
            return jsThis;
        } else {
            // 使用\`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;
            }
    
            napi\_value cons = nullptr;
            const char\* constructorName = "MyObject";
            status = napi\_get\_named\_property(env, jsThis, constructorName, &cons);
            if (status != napi\_ok) {
                napi\_throw\_error(env, nullptr, "Node-API napi\_get\_named\_property 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.  将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将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap(env, jsThis, reinterpret\_cast<void\*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap 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将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap(env, jsThis, reinterpret\_cast<void\*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap 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将jsThis之前绑定的C++对象取出，并对其进行操作
        status = napi\_unwrap(env, jsThis, reinterpret\_cast<void\*\*>(&obj));
        if (status != napi\_ok) {
            napi\_throw\_error(env, nullptr, "Node-API napi\_unwrap 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);
    }