整体思路:arkts使用多线程的方式向c++传递回调方法,c++使用多线程调用回调方法。
定义方法
src/main/cpp/types/libentry/Index.d.ts
export const setCallback: (cb: (a: number) => number) => number;
新建线程,传递回调方法
src/main/ets/entryability/NativePlugin.ets
import tunnel from 'libentry.so';
import { taskpool } from '@kit.ArkTS';
@Concurrent
function callbackFun(c: number,b:number){
tunnel.setCallback((a: number)=>{
console.log('cb~~ result: %d', a, b);
return 0;
});
}
let task:taskpool.Task = new taskpool.Task(callbackFun,5,4);
// 执行多线程任务
taskpool.execute(task, taskpool.Priority.HIGH);
c++多线程执行回调
src/main/cpp/NativeAPI.cpp
#include <thread>
// Global reference to store the JavaScript callback
napi_ref callbackRef;
napi_env globalEnv;
void CallJSCallback(int result) {
napi_handle_scope scope;
napi_open_handle_scope(globalEnv, &scope);
napi_value callback;
napi_get_reference_value(globalEnv, callbackRef, &callback);
napi_value global;
napi_get_global(globalEnv, &global);
napi_value argv[1];
napi_create_int32(globalEnv, result, &argv[0]);
napi_call_function(globalEnv, global, callback, 1, argv, nullptr);
napi_close_handle_scope(globalEnv, scope);
}
void AsyncWork() {
std::this_thread::sleep_for(std::chrono::seconds(1)); // Simulate some async work
CallJSCallback(42); // Call the JS callback with the result
}
// Native method to set the callback
napi_value SetCallback(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
globalEnv = env; // Store the environment for later use
napi_create_reference(env, args[0], 1, &callbackRef); // Store the callback reference
// Start async work in a new thread
std::thread worker(AsyncWork);
worker.detach(); // Detach the thread so it can run independently
return nullptr; // Return nothing
}
// 执行回调
CallJSCallback(11);
// 绑定映射
{ "setCallback", 0, SetCallback, 0, 0, 0, napi_default, 0 },