ArkTS的function传递给C后,如何在C的子线程使用该function

ArkTS的function传递给C后,如何在C的子线程使用该function

HarmonyOS
2024-01-31 18:43:30
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fldj

当C创建了其他的线程,创建的其他的线程不能直接调用ArkTS侧的函数,必须要跟C主线程通信,然后通过主线程来调用ArkTS回调函数。

参照如下代码:

ArkTS侧传入回调函数:

Text(this.message) 
    .onClick(() => { 
        testNapi.threadSafeTest((value) => { 
            hilog.info(0x0000, 'testTag', 'js callback value = ' + value); 
        }) 
    })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

Native侧主线程中创建线程安全函数:

napi_ref cbObj = nullptr; 
napi_threadsafe_function tsfn; 
#define NUMBER 666 
static void CallJs(napi_env env, napi_value js_cb, void *context, void *data) { 
  napi_get_reference_value(env, cbObj, &js_cb); 
  napi_value argv; 
  napi_create_int32(env, NUMBER, &argv); 
  napi_value result = nullptr; 
  napi_call_function(env, nullptr, js_cb, 1, &argv, &result); 
}
static napi_value ThreadSafeTest(napi_env env, napi_callback_info info) { 
    size_t argc = 1; 
    napi_value js_cb, work_name; 
    napi_status status; 
    napi_get_cb_info(env, info, &argc, &js_cb, nullptr, nullptr); 
    status = napi_create_reference(env, js_cb, 1, &cbObj); 
    OH_LOG_INFO(LOG_APP, " ThreadSafeTest 0 : %{public}d ", status == napi_ok); 
    // Set initial_refcount to 0 for a weak reference, >0 for a strong reference. 
    status = napi_create_reference(env, js_cb, 1, &cbObj); 
    OH_LOG_INFO(LOG_APP, " napi_create_reference of js_cb to cbObj : %{public}d", status == napi_ok); 
    status = napi_create_string_utf8(env, "Node-API Thread-safe call from Async work Item", NAPI_AUTO_LENGTH, &work_name); 
    status = napi_create_threadsafe_function(env, js_cb, NULL, work_name, 0, 1, NULL, NULL, NULL, CallJs, &tsfn); 
    OH_LOG_INFO(LOG_APP, "napi_create_threadsafe_function : %{public}d", status == napi_ok); 
    std::thread t( { 
        std::thread::id this_id = std::this_thread::get_id(); 
        OH_LOG_INFO(LOG_APP, "thread0 %{public}s.\n", this_id); 
        napi_status status; 
        status = napi_acquire_threadsafe_function(tsfn); 
        OH_LOG_INFO(LOG_APP, "thread : %{public}d", status == napi_ok); 
        napi_call_threadsafe_function(tsfn, NULL, napi_tsfn_blocking); 
    }); 
    t.detach(); 
    return nullptr; 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.

上面代码中,ArkTS调用ThreadsTest方法,通过napi_create_threadsafe_function() 创建了一个NAPI对象,该对象包含一个ArkTS函数,并且可以从多个线程调用。

分享
微博
QQ
微信
回复
2024-02-01 21:42:43
相关问题
如何在C/C++ 创建ArkTS对象
3484浏览 • 1回复 待解决
如何实现ArkTSC/C++对象传递
1751浏览 • 1回复 待解决
如何实现ArkTSC/C++数组转换
1806浏览 • 1回复 待解决
如何实现ArkTSC/C++HashMap转换?
2174浏览 • 0回复 待解决