DEV Community

HarmonyOS
HarmonyOS

Posted on

Node-API Part-3: Wrapping a Native C++ Object in a Sendable ArkTS Class

Read the original article:Node-API Part-3: Wrapping a Native C++ Object in a Sendable ArkTS Class

🔄 Node-API Part-3: Wrapping a Native C++ Object in a Sendable ArkTS Class

When building HarmonyOS applications that bridge native performance with ArkTS flexibility, you may need to safely expose native C++ objects to your JavaScript/ArkTS logic. That’s where napi_wrap_sendable and napi_unwrap_sendable comes into play.

This guide walks you through how to wrap a C++ object in a sendable ArkTS class , enabling safe cross-context operations and improved memory handling, using a working example.

🎯 Why Use Sendable Objects?

In many applications, native objects must be:

  • Passed across thread boundaries.
  • Exchanged between JS workers or modules.
  • Maintained across lifecycle changes without memory leaks.

The @Sendable decorator in ArkTS, together with native registration using N-API, makes this not only possible but clean and efficient.

🏗️ Step-by-Step: Building a Sendable Wrapper

Let’s build a native class called MyObject, expose it to ArkTS and operate on it safely.

1. 📁 API Declaration in index.d.ts


@Sendable

export class MyObject {
  constructor(arg: number);

  plusOne(): number;

  public get value();

  public set value(newVal: number);
}
Enter fullscreen mode Exit fullscreen mode

API Interface Declaration
This tells ArkTS that MyObject is safe to pass across threads and contexts.

2. 📁 Main Logics in napi_init.cpp

Every time you want to access or modify the native object, you can use napi_unwrap_sendable


// napi_init.cpp
#include "napi/native_api.h"
#include "hilog/log.h"

// A native C++ class wrapped as a sendable object accessible from ArkTS.
class MyObject {
public:
    // Initializes the MyObject class and exports it to JS.
    static napi_value Init(napi_env env, napi_value exports);

    // Called when the native object is garbage-collected.
    static void Destructor(napi_env env, void *nativeObject, void *finalize_hint);

private:
    // Constructor to initialize internal value.
    explicit MyObject(double value_ = 0);

    // Destructor.
    ~MyObject();

    // Called when JS creates a new instance of MyObject.
    static napi_value New(napi_env env, napi_callback_info info);

    // JS getter for the 'value' property.
    static napi_value GetValue(napi_env env, napi_callback_info info);

    // JS setter for the 'value' property.
    static napi_value SetValue(napi_env env, napi_callback_info info);

    // Increments the internal value by one and returns the result.
    static napi_value PlusOne(napi_env env, napi_callback_info info);

    double value_;  // Internal numeric value
    napi_env env_;  // N-API environment
};

static thread_local napi_ref g_ref = nullptr;

MyObject::MyObject(double value) : value_(value), env_(nullptr) {}

MyObject::~MyObject() {}

// Finalizer called when the JS object is garbage-collected.
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();
}

// Initializes the MyObject class and attaches it to the exports object.
napi_value MyObject::Init(napi_env env, napi_value exports) {
    napi_value num;
    napi_create_double(env, 0, &num);
    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;
    // Defines a sendable class named MyObject.
    napi_define_sendable_class(env, "MyObject", NAPI_AUTO_LENGTH, New, nullptr,
                               sizeof(properties) / sizeof(properties[0]), properties, nullptr, &cons);

    napi_create_reference(env, cons, 1, &g_ref);
    // Attaches the constructor to the module exports.
    napi_set_named_property(env, exports, "MyObject", cons);
    return exports;
}

EXTERN_C_START
// Module initialization entry point.
static napi_value Init(napi_env env, napi_value exports) {
    MyObject::Init(env, exports);
    return exports;
}
EXTERN_C_END

// Module definition used by Node-API to register this native addon.
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},
};

// Called automatically when the shared object is loaded to register the module.
extern "C" __attribute__((constructor)) void RegisterObjectWrapModule() {
    napi_module_register(&nativeModule);
}

// Constructor function for MyObject, handles both `new MyObject()` and direct calls.
napi_value MyObject::New(napi_env env, napi_callback_info info) {
    OH_LOG_INFO(LOG_APP, "MyObject::New called");

    napi_value newTarget;
    napi_get_new_target(env, info, &newTarget);
    if (newTarget != nullptr) {
        // Called as constructor: `new MyObject(...)`
        size_t argc = 1;
        napi_value args[1];
        napi_value jsThis;
        napi_get_cb_info(env, info, &argc, args, &jsThis, nullptr);

        double value = 0.0;
        napi_valuetype valuetype;
        napi_typeof(env, args[0], &valuetype);
        if (valuetype != napi_undefined) {
            napi_get_value_double(env, args[0], &value);
        }

        MyObject *obj = new MyObject(value);
        obj->env_ = env;

        // Wrap native C++ object in a sendable JS object.
        napi_wrap_sendable(env, jsThis, reinterpret_cast<void *>(obj), MyObject::Destructor, nullptr);

        return jsThis;
    } else {
        // Called without `new`: `MyObject(...)`
        size_t argc = 1;
        napi_value args[1];
        napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

        napi_value cons;
        napi_get_reference_value(env, g_ref, &cons);
        napi_value instance;
        napi_new_instance(env, cons, argc, args, &instance);

        return instance;
    }
}

// Getter for the 'value' property.
napi_value MyObject::GetValue(napi_env env, napi_callback_info info) {
    OH_LOG_INFO(LOG_APP, "MyObject::GetValue called");

    napi_value jsThis;
    napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, nullptr);

    MyObject *obj;
    // Retrieve native object from JS wrapper.
    napi_unwrap_sendable(env, jsThis, reinterpret_cast<void **>(&obj));
    napi_value num;
    napi_create_double(env, obj->value_, &num);

    return num;
}

// Setter for the 'value' property.
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;
    napi_value jsThis;

    napi_get_cb_info(env, info, &argc, &value, &jsThis, nullptr);

    MyObject *obj;
    napi_unwrap_sendable(env, jsThis, reinterpret_cast<void **>(&obj));
    napi_get_value_double(env, value, &obj->value_);

    return nullptr;
}

// Increments the value by 1 and returns the updated value.
napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) {
    OH_LOG_INFO(LOG_APP, "MyObject::PlusOne called");

    napi_value jsThis;
    napi_get_cb_info(env, info, nullptr, nullptr, &jsThis, nullptr);

    MyObject *obj;
    napi_unwrap_sendable(env, jsThis, reinterpret_cast<void **>(&obj));
    obj->value_ += 1;

    napi_value num;
    napi_create_double(env, obj->value_, &num);

    return num;
}

Enter fullscreen mode Exit fullscreen mode

napi_init.cpp

3. Use in ArkTS

Your C++ object is now fully controlled from ArkTS with thread-safe, memory-managed access. 💥

import hilog from '@ohos.hilog';
import { MyObject } from 'libentry.so';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {

            let object: MyObject = new MyObject(0);
            object.value = 1023;
            hilog.info(0x0000, 'XXX testTag', 'MyObject value after set: %{public}d', object.value);
            hilog.info(0x0000, 'XXX testTag', 'MyObject plusOne: %{public}d', object.plusOne());

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

Enter fullscreen mode Exit fullscreen mode

index.ets(Only ArkTS Class on project — Caller Script)

4. Set config in CMakeList.txt

# 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)
Enter fullscreen mode Exit fullscreen mode

MainConfig File

🧠 Conclusion

Bridging ArkTS with native C++ code in HarmonyOS doesn’t have to be scary. With sendable objects:

  • ✅ You maintain clear ownership and lifecycle of native objects.
  • 🔁 You gain safe access from multiple contexts.
  • 🚀 You unlock high-performance native modules within the ArkTS ecosystem.

Next time you need to wrap native logic in a scalable, multi-threaded app, you know what tools to reach for.

📚 Resources

Document
The OpenCms demo, brought to you by Alkacon Software.developer.huawei.com

Written by Bunyamin Eymen Alagoz

Top comments (0)