c++主动调用arkts方法

整体思路: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 },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值