• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Wrapping a Native Object in an ArkTS Object
2
3## When to Use
4
5You can use **napi_wrap** to wrap a C++ object in an ArkTS object, and use **napi_unwrap** to retrieve the C++ object previously wrapped in the ArkTS object for subsequent operations.
6
7## Example
8
91. Declare the APIs, configure compile settings, and register the modules.
10
11   **Declare the APIs.**
12
13   ```ts
14   // index.d.ts
15   export class MyObject {
16      constructor(arg: number);
17      plusOne: () => number;
18
19      public get value();
20      public set value(newVal: number);
21   }
22   ```
23
24   **Configure compile settings.**
25
26   ```
27   # Minimum version of CMake.
28   cmake_minimum_required(VERSION 3.5.0)
29   project(napi_wrap_demo)
30
31   set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
32
33   if(DEFINED PACKAGE_FIND_FILE)
34       include(${PACKAGE_FIND_FILE})
35   endif()
36
37   include_directories(${NATIVERENDER_ROOT_PATH}
38                       ${NATIVERENDER_ROOT_PATH}/include)
39
40   add_definitions("-DLOG_DOMAIN=0x0000")
41   add_definitions("-DLOG_TAG=\"testTag\"")
42
43   add_library(entry SHARED napi_init.cpp)
44   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so)
45   ```
46
47   **Register modules.**
48
49   ```cpp
50   // napi_init.cpp
51   #include "napi/native_api.h"
52   #include "hilog/log.h"
53
54   class MyObject {
55    public:
56     static napi_value Init(napi_env env, napi_value exports);
57     static void Destructor(napi_env env, void* nativeObject, void* finalize_hint);
58
59    private:
60     explicit MyObject(double value_ = 0);
61     ~MyObject();
62
63     static napi_value New(napi_env env, napi_callback_info info);
64     static napi_value GetValue(napi_env env, napi_callback_info info);
65     static napi_value SetValue(napi_env env, napi_callback_info info);
66     static napi_value PlusOne(napi_env env, napi_callback_info info);
67
68     double value_;
69     napi_env env_;
70     napi_ref wrapper_;
71   };
72
73   static thread_local napi_ref g_ref = nullptr;
74
75   MyObject::MyObject(double value)
76       : value_(value), env_(nullptr), wrapper_(nullptr) {}
77
78   MyObject::~MyObject()
79   {
80     napi_delete_reference(env_, wrapper_);
81   }
82
83   void MyObject::Destructor(napi_env env,
84                             void* nativeObject,
85                             [[maybe_unused]] void* finalize_hint)
86   {
87     OH_LOG_INFO(LOG_APP, "MyObject::Destructor called");
88     reinterpret_cast<MyObject*>(nativeObject)->~MyObject();
89   }
90
91   napi_value MyObject::Init(napi_env env, napi_value exports)
92   {
93     napi_property_descriptor properties[] = {
94         { "value", 0, 0, GetValue, SetValue, 0, napi_default, 0 },
95         { "plusOne", nullptr, PlusOne, nullptr, nullptr, nullptr, napi_default, nullptr }
96     };
97
98     napi_value cons;
99     napi_define_class(env, "MyObject", NAPI_AUTO_LENGTH, New, nullptr, 2,
100                              properties, &cons);
101
102     napi_create_reference(env, cons, 1, &g_ref);
103     napi_set_named_property(env, exports, "MyObject", cons);
104     return exports;
105   }
106
107   EXTERN_C_START
108   static napi_value Init(napi_env env, napi_value exports)
109   {
110       MyObject::Init(env, exports);
111       return exports;
112   }
113   EXTERN_C_END
114
115   static napi_module nativeModule = {
116       .nm_version = 1,
117       .nm_flags = 0,
118       .nm_filename = nullptr,
119       .nm_register_func = Init,
120       .nm_modname = "entry",
121       .nm_priv = nullptr,
122       .reserved = { 0 },
123   };
124
125   extern "C" __attribute__((constructor)) void RegisterObjectWrapModule()
126   {
127       napi_module_register(&nativeModule);
128   }
129   ```
130
1312. Wrap a C++ object in an ArkJS object in a constructor.
132
133   ```cpp
134   napi_value MyObject::New(napi_env env, napi_callback_info info)
135   {
136     OH_LOG_INFO(LOG_APP, "MyObject::New called");
137
138     napi_value newTarget;
139     napi_get_new_target(env, info, &newTarget);
140     if (newTarget != nullptr) {
141       // Invoked as the constructor `new MyObject(...)`.
142       size_t argc = 1;
143       napi_value args[1];
144       napi_value jsThis;
145       napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr);
146
147       double value = 0.0;
148       napi_valuetype valuetype;
149       napi_typeof(env, args[0], &valuetype);
150       if (valuetype != napi_undefined) {
151         napi_get_value_double(env, args[0], &value);
152       }
153
154       MyObject* obj = new MyObject(value);
155
156       obj->env_ = env;
157       // Use napi_wrap to wrap the C++ object obj in the ArkTS object jsThis.
158       napi_wrap(env,
159                 jsThis,
160                 reinterpret_cast<void*>(obj),
161                 MyObject::Destructor,
162                 nullptr,  // finalize_hint
163                 &obj->wrapper_);
164
165       return jsThis;
166     } else {
167       // Invoked as the plain function `MyObject(...)`.
168       size_t argc = 1;
169       napi_value args[1];
170       napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
171
172       napi_value cons;
173       napi_get_reference_value(env, g_ref, &cons);
174       napi_value instance;
175       napi_new_instance(env, cons, argc, args, &instance);
176
177       return instance;
178     }
179   }
180   ```
181
1823. Retrieve the C++ object from the ArkTS object and perform subsequent operations on the C++ object.
183
184   ```cpp
185   napi_value MyObject::GetValue(napi_env env, napi_callback_info info)
186   {
187     OH_LOG_INFO(LOG_APP, "MyObject::GetValue called");
188
189     napi_value jsThis;
190     napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, nullptr);
191
192     MyObject* obj;
193     // Use napi_unwrap to retrieve obj (the C++ object) previously wrapped in jsThis (the ArkTS object), and perform subsequent operations.
194     napi_unwrap(env, jsThis, reinterpret_cast<void**>(&obj));
195     napi_value num;
196     napi_create_double(env, obj->value_, &num);
197
198     return num;
199   }
200
201   napi_value MyObject::SetValue(napi_env env, napi_callback_info info)
202   {
203     OH_LOG_INFO(LOG_APP, "MyObject::SetValue called");
204
205     size_t argc = 1;
206     napi_value value;
207     napi_value jsThis;
208
209     napi_get_cb_info(env, info, &argc, &value, &jsThis, nullptr);
210
211     MyObject* obj;
212     // Use napi_unwrap to retrieve obj (the C++ object) previously wrapped in jsThis (the ArkTS object), and perform subsequent operations.
213     napi_unwrap(env, jsThis, reinterpret_cast<void**>(&obj));
214     napi_get_value_double(env, value, &obj->value_);
215
216     return nullptr;
217   }
218
219   napi_value MyObject::PlusOne(napi_env env, napi_callback_info info)
220   {
221     OH_LOG_INFO(LOG_APP, "MyObject::PlusOne called");
222
223     napi_value jsThis;
224     napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, nullptr);
225
226     MyObject* obj;
227     // Use napi_unwrap to retrieve obj (the C++ object) previously wrapped in jsThis (the ArkTS object), and perform subsequent operations.
228     napi_unwrap(env, jsThis, reinterpret_cast<void**>(&obj));
229     obj->value_ += 1;
230     napi_value num;
231     napi_create_double(env, obj->value_, &num);
232
233     return num;
234   }
235   ```
236
2374. The following provides the sample ArkTS code.
238
239   ```ts
240   import hilog from '@ohos.hilog';
241   import { MyObject } from 'libentry.so';
242
243   let object : MyObject = new MyObject(0);
244   object.value = 1023;
245   hilog.info(0x0000, 'testTag', 'MyObject value after set: %{public}d', object.value);
246   hilog.info(0x0000, 'testTag', 'MyObject plusOne: %{public}d', object.plusOne());
247   ```
248