中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
当前native侧,基于napi,调用js侧类方法的流程为:
1. native层获取到js传入的类object
2. 从Object获取到某个方法名(例如 “getFunc”)
3. 调用getFunc方法,实现native调用js侧实例类方法
但是目前需要native调用某个js类的静态方法,那么应该如何调用呢?预期是不需要实例化该类,即可调用。
微信扫码分享
import { CustomButton } from '../common/CustomButton'; import { Logger } from '../common/Logger'; import libappentry from 'libappentry.so'; const log: Logger = new Logger('NAPIFuncPage'); @Entry @Component struct NAPIFuncPage { build() { Column() { // 增加一个按钮点击调用native接口 CustomButton({ mTitle: '点击调用native方法' }).onClick(() => libappentry.callStaticMethod(TsClass)) } .width('100%').alignItems(HorizontalAlign.Start) } } export class TsClass { // 这里定义一个类 public static TsMethod(): void { // 这里定义一个静态方法 log.info('do static TsMethod'); } } // index.d.ts 导出接口 export const callStaticMethod: (className: Object) => void; // native侧实现参考 static napi_value ts_callStaticMethod(napi_env env, napi_callback_info info) { OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, LOG_TAG, "ts_callStaticMethod"); size_t argc = 1; napi_value js_Class_name; // 取出类名 napi_get_cb_info(env, info, &argc, &js_Class_name, nullptr, nullptr); napi_value staticMethod; // 直接调用类名下的静态方法 napi_get_named_property(env, js_Class_name, "TsMethod", &staticMethod); napi_call_function(env, js_Class_name, staticMethod, 0, nullptr, nullptr); return nullptr; } void FunctionC::Export(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { {"callStaticMethod", nullptr, ts_callStaticMethod, nullptr, nullptr, nullptr, napi_default, nullptr}}; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, LOG_TAG, "Export"); }