HarmonyOS NEXT应用开发之NAPI封装ArkTS接口案例_harmonyos napi

std::unique_lockstd::mutex unil(uniContext->resultWaitUtil.lock);
uniContext->resultWaitUtil.cv.wait(unil, [] { return uniContext->resultWaitUtil.isFinished; });
return;
} else {
status = napi_call_function(uniContext->pickerEnv, nullptr, tsSelect, 4, args, &result);
}

  1. 因为napi中的线程安全函数只能通过napi_threadsafe_function_call_js中的data参数进行传参,因此需要将所需参数全部封装到一个对象中

DocumentViewPickerSelectParam *selectParam = new DocumentViewPickerSelectParam(options, thenWrapper, catchWrapper)

  1. 因为本例中的filepicker是异步的,回调函数需要调用者传入,而napi中若需要将native方法直接封装为ets方法对于函数类型是有要求的。因此这里通过将回调函数封装到对象中,通过对象包装来实现将一般类型的函数封装为ets侧的函数:

native侧:

// step:类型声明
class DocumentViewPickerSelectThenCbWrapper {
public:
documentSelectThenFn thenFn;
DocumentViewPickerSelectThenCbWrapper(documentSelectThenFn fn) : thenFn(fn) {}
/**

  • 将对象实例包装为js对象
    /
    napi_value convert2NapiValue(napi_env env);
    /
    *
  • 参数是string[],这里面会调用thenFn,ets侧调用
    */
    static napi_value call(napi_env env, napi_callback_info info);
    };
    // step2:convert2NapiValue方法实现
    napi_value etswrapper::DocumentViewPickerSelectThenCbWrapper::convert2NapiValue(napi_env env) { <

你可能感兴趣的:(2024年程序员学习,harmonyos,华为)