鸿蒙Next NDK中napi_define_class如何使用

在鸿蒙Next的NDK开发中,使用napi_define_class时遇到问题。按照官方文档尝试封装C++类到JS环境,但总是返回napi_invalid_arg错误。具体代码如下:

napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"testMethod", 0, TestMethod, 0, 0, 0, napi_default, 0}
    };
    napi_value result;
    napi_status status = napi_define_class(
        env, 
        "MyClass", 
        NAPI_AUTO_LENGTH, 
        Constructor, 
        nullptr, 
        sizeof(desc)/sizeof(desc[0]), 
        desc, 
        &result
    );
    // 这里status总是返回napi_invalid_arg
}

请问:

  1. 参数传递是否有遗漏或错误?
  2. Constructor回调函数是否需要特定实现规范?
  3. 鸿蒙Next对NAPI的封装是否存在特殊限制?

更多关于鸿蒙Next NDK中napi_define_class如何使用的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

哈哈,程序员老哥,napi_define_class就像给鸿蒙NDK里的JS“相亲”一个C++类!用法超简单:

  1. 先准备构造函数和一堆方法属性
  2. 调用napi_define_class(env, 类名, 构造函数, 方法数组, 属性数组)
  3. 返回的napi_value就是你的“相亲成功”的类对象

记得方法数组要以nullptr结尾,不然JS会跟你急眼!

更多关于鸿蒙Next NDK中napi_define_class如何使用的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next NDK中,napi_define_class 用于定义JavaScript类,将C++类或结构体绑定到JavaScript环境。以下是使用步骤和示例:

函数原型

napi_status napi_define_class(napi_env env,
                              const char* name,
                              size_t length,
                              napi_callback constructor,
                              void* data,
                              size_t property_count,
                              const napi_property_descriptor* properties,
                              napi_value* result);

参数说明

  • env: NAPI环境句柄
  • name: 类名
  • length: 类名长度(NAPI_AUTO_LENGTH可自动计算)
  • constructor: 构造函数回调
  • data: 传递给回调的额外数据
  • property_count: 属性数量
  • properties: 属性描述符数组
  • result: 返回定义的类

使用示例

  1. 定义构造函数
napi_value MyClassConstructor(napi_env env, napi_callback_info info) {
    napi_value this_arg;
    napi_get_cb_info(env, info, NULL, NULL, &this_arg, NULL);
    
    // 初始化C++对象(示例)
    MyClass* obj = new MyClass();
    napi_wrap(env, this_arg, obj, NULL, NULL, NULL);
    
    return this_arg;
}
  1. 定义类方法
napi_value GetValue(napi_env env, napi_callback_info info) {
    MyClass* obj;
    napi_value this_arg;
    napi_get_cb_info(env, info, NULL, NULL, &this_arg, NULL);
    napi_unwrap(env, this_arg, (void**)&obj);
    
    napi_value result;
    napi_create_int32(env, obj->getValue(), &result);
    return result;
}
  1. 定义属性描述符
napi_property_descriptor desc[] = {
    { "getValue", NULL, GetValue, NULL, NULL, NULL, napi_default, NULL }
};
  1. 注册类
napi_value Init(napi_env env, napi_value exports) {
    napi_value my_class;
    napi_define_class(env, "MyClass", NAPI_AUTO_LENGTH, MyClassConstructor, 
                      NULL, 1, desc, &my_class);
    napi_set_named_property(env, exports, "MyClass", my_class);
    return exports;
}

注意事项

  • 使用 napi_wrap 将C++对象绑定到JavaScript实例
  • 通过 napi_unwrap 在方法中获取C++对象
  • 确保内存管理正确,避免泄漏

这样即可在JavaScript中通过 new MyClass() 创建实例并调用绑定方法。

回到顶部