中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
需要提供c++到js通信demo
微信扫码分享
#include “napi/native_api.h” #include “uv.h” #include <iostream> #include <sound/hdsp.h> #include <stdio.h> #include <thread> #include <hilog/log.h> #define LOG_TAG “thfTest” napi_threadsafe_function tsfn; napi_ref cbObj = nullptr; static void NativeThread(void *data) { std::cout << "NativeThread " << std::this_thread::get_id() << std::endl; napi_call_threadsafe_function(tsfn, nullptr, napi_tsfn_blocking); // Release the thread-safe function. This causes it to be cleaned up in the // background. napi_release_threadsafe_function(tsfn, napi_tsfn_release); } static void CallJs(napi_env env, napi_value js_cb, void* context, void* data) { if (env != nullptr) { napi_status status; napi_value undefined, js_the_prime; status = napi_get_undefined(env, &undefined); status = napi_get_reference_value(env, cbObj, &js_cb); status = napi_call_function(env, undefined, js_cb, 0, nullptr, nullptr); OH_LOG_INFO(LOG_APP, “thf test3: CallJs%{public}d”, status); if (status != napi_ok) { OH_LOG_INFO(LOG_APP, “thf test3”); } } } static napi_value startThread(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value js_cb, work_name; napi_get_cb_info(env, info, &argc, &js_cb, nullptr, nullptr); napi_create_string_utf8(env, “Thread-safe Function Round Trip Example”, NAPI_AUTO_LENGTH, &work_name); napi_create_threadsafe_function(env, js_cb, nullptr, work_name, 0, 1, nullptr, nullptr, nullptr, CallJs, &tsfn); uv_thread_t new_thread; uv_thread_create(&new_thread, NativeThread, nullptr); return nullptr; } EXTERN_C_START static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { { “startThread”, nullptr, startThread, nullptr, nullptr, nullptr, napi_default, nullptr } }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); return exports; } EXTERN_C_END static napi_module demoModule = { .nm_version =1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = Init, .nm_modname = “entry”, .nm_priv = ((void*)0), .reserved = { 0 }, }; extern “C” attribute((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); } index.ets import hilog from ‘@ohos.hilog’; import testNapi from ‘libentry.so’; function jsCallback() { console.log("jsCallback called "); } @Entry @Component struct Index { @State message: string = ‘Hello World’; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { hilog.info(0x0000, ‘testTag’, ‘Test NAPI 2 + 3 = %{public}d’, testNapi.add(2, 3)); testNapi.startThread(jsCallback); }) } .width(‘100%’) } .height(‘100%’) } }