文档管理中心
FAQ应用框架开发NDK开发NDK开发NAPI执行上层回调时,如何获取env

NAPI执行上层回调时,如何获取env

libuv处理方式是在注册JS回调时保存env。在callback中从env中获取对应的JS线程的loop,再调用libuv接口抛JS任务到loop中执行。

napi_create_thread_safe_function函数调用时会触发参数中的napi_threadsafe_function_call_js函数,该函数可以获取env在js线程中执行,参考以下方式:

收起
自动换行
深色代码主题
复制
  1. #include "napi/native_api.h"
  2. #include <thread>
  3. #include "hilog/log.h"
  4. napi_ref cbObj = nullptr;
  5. // Thread safety function
  6. napi_threadsafe_function tsfn;
  7. // Native side Value Value
  8. static int cValue;
  9. // Subthread running function
  10. static void CallJs(napi_env env, napi_value js_cb, void *context, void *data) {
  11. std::thread::id this_id = std::this_thread::get_id();
  12. OH_LOG_INFO(LOG_APP, "threadId3 is +%{public}d", this_id);
  13. // Get reference value
  14. napi_get_reference_value(env, cbObj, &js_cb);
  15. // Create an ArkTS number as an input parameter for the ArkTS function.
  16. napi_value argv;
  17. napi_create_int32(env, cValue, &argv);
  18. napi_value result = nullptr;
  19. napi_call_function(env, nullptr, js_cb, 1, &argv, &result);
  20. napi_get_value_int32(env, result, &cValue);
  21. napi_delete_reference(env, cbObj);
  22. }
  23. // Native main thread
  24. static napi_value ThreadsTest(napi_env env, napi_callback_info info) {
  25. // The number of parameters obtained from ArkTS side
  26. size_t argc = 1;
  27. napi_value js_cb, work_name;
  28. // Get ArkTS parameters
  29. napi_get_cb_info(env, info, &argc, &js_cb, nullptr, nullptr);
  30. // Napi_ref cbObj pointing to napi_value js_cb
  31. napi_create_reference(env, js_cb, 1, &cbObj);
  32. // Create workname using UTF8 encoded C string data
  33. napi_create_string_utf8(env, "Work Item", NAPI_AUTO_LENGTH, &work_name);
  34. // Create thread safe function
  35. napi_create_threadsafe_function(env, js_cb, NULL, work_name, 0, 1, NULL, NULL, NULL, CallJs, &tsfn);
  36. std::thread::id this_id = std::this_thread::get_id();
  37. OH_LOG_INFO(LOG_APP, "threadId1 is +%{public}d", this_id);
  38. // Calling thread safe functions in other threads
  39. std::thread t([]() {
  40. // Can obtain thread ID
  41. std::thread::id this_id = std::this_thread::get_id();
  42. OH_LOG_INFO(LOG_APP, "threadId2 is +%{public}d", this_id);
  43. napi_acquire_threadsafe_function(tsfn);
  44. napi_call_threadsafe_function(tsfn, NULL, napi_tsfn_blocking);
  45. });
  46. t.detach();
  47. return NULL;
  48. }
在 FAQ 中进行搜索
请输入您想要搜索的关键词