From 0947cfd569b6e1e0f3a1ae86eea3936f1deb343e Mon Sep 17 00:00:00 2001 From: birdswu Date: Thu, 15 May 2025 17:32:31 +0800 Subject: [PATCH 1/9] =?UTF-8?q?ArkTs=20=E6=A0=87=E8=AE=B0=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pages/GlobalThisReplacementInArkTS.ets | 39 +------------------ .../src/main/ets/pages/ThisUsageInArkTS.ets | 4 +- ArkTS/entry/src/main/ets/utils/globalThis.ets | 38 ++++++++++++++++++ 3 files changed, 42 insertions(+), 39 deletions(-) create mode 100644 ArkTS/entry/src/main/ets/utils/globalThis.ets diff --git a/ArkTS/entry/src/main/ets/pages/GlobalThisReplacementInArkTS.ets b/ArkTS/entry/src/main/ets/pages/GlobalThisReplacementInArkTS.ets index ae48eff..7fa9e2c 100644 --- a/ArkTS/entry/src/main/ets/pages/GlobalThisReplacementInArkTS.ets +++ b/ArkTS/entry/src/main/ets/pages/GlobalThisReplacementInArkTS.ets @@ -12,47 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - /* * FAQ:ArkTS中globalThis无法使用该如何替换 */ -// DocsCode 1 -import { common } from '@kit.AbilityKit'; - -// 构造单例对象 -export class GlobalThis { - private constructor() {}; - private static instance: GlobalThis; - private _uiContexts = new Map(); - private value = ''; - - public static getInstance(): GlobalThis { - if (!GlobalThis.instance) { - GlobalThis.instance = new GlobalThis(); - } - return GlobalThis.instance; - } - - getContext(key: string): common.UIAbilityContext | undefined { - return this._uiContexts.get(key); - } - - setContext(key: string, value: common.UIAbilityContext): void { - this._uiContexts.set(key, value); - } - - setValue(value:string){ - this.value = value - } - - getValue():string{ - return this.value; - } -} -// DocsCode 1 -// DocsCode 2 +// [Start globalThis2] import { GlobalThis } from '../utils/globalThis'; @Entry @@ -84,4 +49,4 @@ struct Index { .height('100%') } } -// DocsCode2 \ No newline at end of file +// [End globalThis2] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/pages/ThisUsageInArkTS.ets b/ArkTS/entry/src/main/ets/pages/ThisUsageInArkTS.ets index d8f9472..99d5d39 100644 --- a/ArkTS/entry/src/main/ets/pages/ThisUsageInArkTS.ets +++ b/ArkTS/entry/src/main/ets/pages/ThisUsageInArkTS.ets @@ -17,7 +17,7 @@ * FAQ:ArkTS中this的常用场景及使用 */ -// DocsCode 1 +// [Start ThisUsageInArkTS] class UserInfo { name: string = 'xxx'; @@ -27,4 +27,4 @@ class UserInfo { } const user: UserInfo = new UserInfo(); -// DocsCode 1 \ No newline at end of file +// [Start ThisUsageInArkTS] \ No newline at end of file diff --git a/ArkTS/entry/src/main/ets/utils/globalThis.ets b/ArkTS/entry/src/main/ets/utils/globalThis.ets new file mode 100644 index 0000000..6f7d087 --- /dev/null +++ b/ArkTS/entry/src/main/ets/utils/globalThis.ets @@ -0,0 +1,38 @@ +/* +* FAQ:ArkTS中globalThis无法使用该如何替换 +*/ + +// [Start globalThis1] +import { common } from '@kit.AbilityKit'; + +// 构造单例对象 +export class GlobalThis { + private constructor() {}; + private static instance: GlobalThis; + private _uiContexts = new Map(); + private value = ''; + + public static getInstance(): GlobalThis { + if (!GlobalThis.instance) { + GlobalThis.instance = new GlobalThis(); + } + return GlobalThis.instance; + } + + getContext(key: string): common.UIAbilityContext | undefined { + return this._uiContexts.get(key); + } + + setContext(key: string, value: common.UIAbilityContext): void { + this._uiContexts.set(key, value); + } + + setValue(value:string){ + this.value = value + } + + getValue():string{ + return this.value; + } +} +// [End globalThis1] \ No newline at end of file -- Gitee From 11f1765c25ca2c1998b933e6980a323913f236ef Mon Sep 17 00:00:00 2001 From: birdswu Date: Thu, 15 May 2025 18:58:26 +0800 Subject: [PATCH 2/9] =?UTF-8?q?NdkDevelopment=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E6=A0=87=E8=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pages/AsyncMethodForArkTSFromNative.ets | 12 +++--- .../src/main/ets/pages/CSideOpenFile.ets | 8 ++-- .../ets/pages/DynamicallyLoadSOLibrary.ets | 12 +++--- .../ets/pages/GetObjectForArkTSFromNative.ets | 4 +- .../src/main/ets/pages/IntegrateSOLibrary.ets | 20 +++++----- .../MultiSoInterdependenceDecoupling.ets | 8 ++-- .../main/ets/pages/NapiModuleStructure.ets | 4 +- .../ets/pages/NativeSideAccessRawfile.ets | 12 +++--- .../pages/NativeSideCrossModuleAccessR.ets | 12 +++--- .../pages/NativeSideOperableFileDirectory.ets | 37 ++++++++++++++++--- .../resources/base/profile/main_pages.json | 3 +- 11 files changed, 79 insertions(+), 53 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets index c9aa22b..7ab9abe 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets @@ -17,7 +17,7 @@ * FAQ:Native侧如何访问ArkTS侧系统定义的异步方法 */ -// DocsCode 1 +// [Start AsyncMethodForArkTSFromNative1] #include "napi/native_api.h" #include #include @@ -111,13 +111,13 @@ static napi_value getDisplayWidthAsync(napi_env env, napi_callback_info info) { napi_create_promise(env, &callbackData->deferred, &result); return result; } -// DocsCode 1 +// [End AsyncMethodForArkTSFromNative1] -// DocsCode 2 +// [Start AsyncMethodForArkTSFromNative2] export const getDisplayWidthAsync: () => Promise; -// DocsCode 2 +// [End AsyncMethodForArkTSFromNative2] -// DocsCode 3 +// [Start AsyncMethodForArkTSFromNative3] import testNapi from 'libcallsystemasyncwork.so'; @Entry @@ -145,4 +145,4 @@ struct Index { .height('100%') } } -// DocsCode 3 \ No newline at end of file +// [End AsyncMethodForArkTSFromNative3] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets b/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets index 5d97914..f2873b2 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets @@ -17,7 +17,7 @@ * FAQ:C侧如何打开文件 */ -// DocsCode 1 +// [Start CSideOpenFile1] import { fileIo, picker } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; import testNapi from 'libentry.so'; @@ -66,9 +66,9 @@ struct Index { .height('100%') } } -// DocsCode 1 +// [End CSideOpenFile1] -// DocsCode 2 +// [Start CSideOpenFile2] static napi_value OpenFile(unsigned int fd, unsigned int fd2) { OH_LOG_INFO(LOG_APP, "OpenFile"); @@ -113,4 +113,4 @@ static napi_value ReadFile(napi_env env, napi_callback_info info) { OpenFile(fd, fd2); return nullptr; } -// DocsCode 2 \ No newline at end of file +// [End CSideOpenFile2] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibrary.ets b/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibrary.ets index 3163a19..ee3d3a0 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibrary.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibrary.ets @@ -17,7 +17,7 @@ * FAQ:ArkTS侧与Native侧分别如何动态加载SO库 */ -// DocsCode 1 +// [Start LoadSoLibrary1] import { hilog } from '@kit.PerformanceAnalysisKit'; // import testNapi from 'libentry.so'; @@ -43,9 +43,9 @@ struct LoadSoLibrary { .height('100%') } } -// DocsCode 1 +// [End LoadSoLibrary1] -// DocsCode 2 +// [Start LoadSoLibrary2] import { hilog } from '@kit.PerformanceAnalysisKit'; import testNapi from 'libentry.so'; @@ -71,9 +71,9 @@ struct Index { .height('100%') } } -// DocsCode 2 +// [End LoadSoLibrary2] -// DocsCode 3 +// [Start LoadSoLibrary3] #include "napi/native_api.h" #include typedef double (*FUNC_ADD)(int, int); @@ -101,4 +101,4 @@ static napi_value Add(napi_env env, napi_callback_info info) { napi_create_double(env, res, &sum); return sum; } -// DocsCode 3 \ No newline at end of file +// [End LoadSoLibrary3] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets b/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets index bb1609a..d70532d 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets @@ -17,7 +17,7 @@ * FAQ:Native侧如何获取ArkTS侧Object对象及其成员变量 */ -// DocsCode 1 +// [Start GetObjectForArkTSFromNative] // index.ets import testNapi from 'libentry.so'; @@ -37,4 +37,4 @@ build() { testNapi.callFunction(new A()); }) } -// DocsCode 1 \ No newline at end of file +// [End GetObjectForArkTSFromNative] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets index 18254a4..4209c2a 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets @@ -17,7 +17,7 @@ * FAQ:在Native侧如何集成三方SO库 */ -// DocsCode 1 +// [Start LoadThirdSoLibrary1] // sub.h extern "C" { double sub(double a, double b); @@ -34,9 +34,9 @@ cmake_minimum_required(VERSION 3.4.1) project(libSub) #编译源码 add_library(nativeSub SHARED sub.cpp) -// DocsCode 1 +// [End LoadThirdSoLibrary1] -// DocsCode 2 +// [Start LoadThirdSoLibrary2] # CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(hello) @@ -46,9 +46,9 @@ ${NATIVERENDER_ROOT_PATH}/include) add_library(library SHARED hello.cpp) target_link_libraries(library PUBLIC libace_napi.z.so libhilog_ndk.z.so) target_link_libraries(library PUBLIC ${NATIVERENDER_ROOT_PATH}/../../../libs/arm64-v8a/libnativeSub.so) -// DocsCode 2 +// [End LoadThirdSoLibrary2] -// DocsCode 3 +// [Start LoadThirdSoLibrary3] #include "sub.h" static napi_value Sub(napi_env env, napi_callback_info info) { @@ -68,9 +68,9 @@ static napi_value Sub(napi_env env, napi_callback_info info) napi_create_double(env, sub(value0 - value1), &sum); return sum; } -// DocsCode 3 +// [End LoadThirdSoLibrary3] -// DocsCode 4 +// [Start LoadThirdSoLibrary4] import { hilog } from '@kit.PerformanceAnalysisKit'; import testNapi from 'libentry.so'; @@ -96,9 +96,9 @@ struct Index { .height('100%') } } -// DocsCode 4 +// [End LoadThirdSoLibrary4] -// DocsCode 5 +// [Start LoadThirdSoLibrary5] #include typedef double (*Sub)(double, double); static napi_value SubSobyDlOpenSo(napi_env env, napi_callback_info info) { @@ -120,4 +120,4 @@ static napi_value SubSobyDlOpenSo(napi_env env, napi_callback_info info) { dlclose(handle); // 最后记得close动态库 return result; } -// DocsCode 5 \ No newline at end of file +// [End LoadThirdSoLibrary5] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets index 508eb05..8daaa16 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets @@ -17,7 +17,7 @@ * FAQ:多so相互依赖场景下如何解耦 */ -// DocsCode 1 +// [Start MultiSoInterdependence1] // a.cpp extern "C" { // 一定要用extern "C" {}括起来 #include "a.h" @@ -78,9 +78,9 @@ target_link_libraries(a PUBLIC libace_napi.z.so libhilog_ndk.z.so) project(libb) add_library(b SHARED b.cpp) // 编译库libb.so target_link_libraries(b PUBLIC libace_napi.z.so libhilog_ndk.z.so) -// DocsCode 1 +// [End MultiSoInterdependence1] -// DocsCode 2 +// [Start MultiSoInterdependence2] // CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(DemoSO) @@ -193,4 +193,4 @@ static napi_module demoModule = { .reserved = {0}, }; extern "C" __attribute__((constructor)) void RegisterDemosoModule(void) { napi_module_register(&demoModule); } -// DocsCode 2 \ No newline at end of file +// [End MultiSoInterdependence2] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets b/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets index d673717..4939f43 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets @@ -17,7 +17,7 @@ * FAQ:napi_module结构体字段描述解析 */ -// DocsCode 1 +// [Start NapiModuleStructure] static napi_module demoModule = { .nm_version = 1, // nm版本号,默认值为1 .nm_flags = 0, // nm标识符 @@ -27,4 +27,4 @@ static napi_module demoModule = { .nm_priv = ((void *)0), // 暂不关注,使用默认即可 .reserved = {0}, // 暂不关注,使用默认值即可 }; -// DocsCode 1 \ No newline at end of file +// [End NapiModuleStructure] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets index 1d674bc..ddd0442 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets @@ -17,12 +17,12 @@ * FAQ:如何在Native侧访问应用包内Rawfile资源 */ -// DocsCode 1 +// [Start NativeSideAccessRawfile1] import { resourceManager } from "@kit.LocalizationKit"; export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// DocsCode 1 +// [End NativeSideAccessRawfile1] -// DocsCode 2 +// [Start NativeSideAccessRawfile2] #include "napi/native_api.h" #include #include @@ -84,9 +84,9 @@ static napi_value GetRawFileContent(napi_env env, napi_callback_info info) // 转为js对象 return CreateJsArrayValue(env, data, len); } -// DocsCode 2 +// [End NativeSideAccessRawfile2] -// DocsCode 3 +// [Start NativeSideAccessRawfile3] import testNapi from 'libnativeaccessres.so' // 导入so @Entry @@ -111,4 +111,4 @@ struct Index { .height('100%') } } -// DocsCode 3 \ No newline at end of file +// [End NativeSideAccessRawfile3] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets b/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets index 91c20a9..d3bf5f0 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets @@ -17,12 +17,12 @@ * FAQ:如何在Native侧跨模块访问资源 */ -// DocsCode 1 +// [Start NativeSideCrossModuleAccessRawfile1] import { resourceManager } from "@kit.LocalizationKit"; export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// DocsCode 1 +// [End NativeSideCrossModuleAccessRawfile1] -// DocsCode 2 +// [Start NativeSideCrossModuleAccessRawfile2] #include "napi/native_api.h" #include #include @@ -84,9 +84,9 @@ static napi_value GetRawFileContent(napi_env env, napi_callback_info info) // 转为js对象 return CreateJsArrayValue(env, data, len); } -// DocsCode 2 +// [End NativeSideCrossModuleAccessRawfile2] -// DocsCode 3 +// [Start NativeSideCrossModuleAccessRawfile3] import testNapi from 'libnativecrossmoduleaccessres.so'; @Entry @@ -111,4 +111,4 @@ struct Index { .height('100%') } } -// DocsCode 3 \ No newline at end of file +// [End NativeSideCrossModuleAccessRawfile3] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets b/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets index 4fb3f43..39a66bb 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets @@ -17,10 +17,37 @@ * FAQ:Native侧如何获取可操作的文件目录 */ -// DocsCode 1 +// [Start NativeSideOperableFileDirectory] import { common } from '@kit.AbilityKit'; -context = this.getUIContext(); -let hostContext = this.context.getHostContext() as common.UIAbilityContext; -let filesDir = hostContext.filesDir; -// DocsCode 1 \ No newline at end of file +// [StartExclude NativeSideOperableFileDirectory] +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + getScreenDensity() { + // [EndExclude NativeSideOperableFileDirectory] + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let screenDensity = context.config.screenDensity; + // [End NativeSideOperableFileDirectory] + } + + build() { + RelativeContainer() { + Text(this.message) + .id('HelloWorld') + .fontSize($r('app.float.page_text_font_size')) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__',align: VerticalAlign.Center }, + middle: { anchor: '__container__',align: HorizontalAlign.Center } + }) + .onClick(() => { + this.message = 'Welcome'; + }) + } + .height('100%') + .width('100%') + } +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json b/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json index 09ab5f8..55c3f00 100644 --- a/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json +++ b/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json @@ -1,6 +1,5 @@ { "src": [ - "pages/Index", - "pages/CSideOpenFile" + "pages/Index" ] } \ No newline at end of file -- Gitee From 83de6f40784dea1fe6ebb8e26593fd077633d533 Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:10:32 +0000 Subject: [PATCH 3/9] update ArkTS/entry/src/main/ets/utils/globalThis.ets. Signed-off-by: birdswu --- ArkTS/entry/src/main/ets/utils/globalThis.ets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ArkTS/entry/src/main/ets/utils/globalThis.ets b/ArkTS/entry/src/main/ets/utils/globalThis.ets index 6f7d087..e8458e1 100644 --- a/ArkTS/entry/src/main/ets/utils/globalThis.ets +++ b/ArkTS/entry/src/main/ets/utils/globalThis.ets @@ -5,7 +5,7 @@ // [Start globalThis1] import { common } from '@kit.AbilityKit'; -// 构造单例对象 +// Construct singleton objects export class GlobalThis { private constructor() {}; private static instance: GlobalThis; -- Gitee From 4db79f1aea6b7be107d104eacbe5350d085bd083 Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:13:57 +0000 Subject: [PATCH 4/9] update NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets. Signed-off-by: birdswu --- .../pages/AsyncMethodForArkTSFromNative.ets | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets index 7ab9abe..13fdd5d 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets @@ -22,9 +22,9 @@ #include #include -#define LOG_TAG "Pure" // 全局tag宏,标识模块日志tag +#define LOG_TAG "Pure" // Global tag macro, identifying module log tags -// 上下文数据,用于线程间传递数据 +// Context data, used for transferring data between threads struct CallbackData { napi_threadsafe_function tsfn; napi_async_work work; @@ -41,12 +41,12 @@ static napi_value ResolvedCallback(napi_env env, napi_callback_info info) { double result = 0; napi_get_value_double(env, widthProp, &result); OH_LOG_INFO(LOG_APP, "width in ResolvedCallback is %{public}f", result); - // data被重新解释为指向std::promise的指针,并设置该promise的值为width + // Data is reinterpreted as a pointer to std:: promiseand the value of the promise is set to width reinterpret_cast *>(data)->set_value(result); return nullptr; } static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) { - // 导入系统库模块,逐层向下调用到方法 + // Import system library modules and call down to methods layer by layer napi_value systemModule; napi_load_module(env, "@ohos.display", &systemModule); napi_value displayFunc = nullptr; @@ -56,7 +56,7 @@ static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) { napi_value thenFunc = nullptr; napi_get_named_property(env, promise, "then", &thenFunc); napi_value resolvedCallback; - // promise resolve回调 + // Promise resolve callback napi_create_function(env, "resolvedCallback", NAPI_AUTO_LENGTH, ResolvedCallback, data, &resolvedCallback); napi_value argv[] = {resolvedCallback}; napi_call_function(env, promise, thenFunc, 1, argv, nullptr); @@ -76,13 +76,13 @@ static void ExecuteWork(napi_env env, void *data) { } static void WorkComplete(napi_env env, napi_status status, void *data) { CallbackData *callbackData = reinterpret_cast(data); - // 回传业务代码计算结果给应用 + // Return the calculation results of the business code to the application napi_value result = nullptr; napi_create_double(env, callbackData->res, &result); napi_resolve_deferred(env, callbackData->deferred, result); - // 释放线程安全方法 + // Release thread safety methods napi_release_threadsafe_function(callbackData->tsfn, napi_tsfn_release); - // 删除异步工作项 + // Delete asynchronous work items napi_delete_async_work(env, callbackData->work); callbackData->tsfn = nullptr; callbackData->work = nullptr; @@ -97,16 +97,16 @@ static napi_value getDisplayWidthAsync(napi_env env, napi_callback_info info) { napi_load_module(env, "@ohos.display", &sysModule); napi_value getDefaultDisplay; napi_get_named_property(env, sysModule, "getDefaultDisplay", &getDefaultDisplay); - // 创建一个线程安全函数 + // Create a thread safe function napi_value resourceName = nullptr; napi_create_string_utf8(env, "getDisplayWidthAsync", NAPI_AUTO_LENGTH, &resourceName); napi_create_threadsafe_function(env, getDefaultDisplay, nullptr, resourceName, 0, 1, callbackData, nullptr, callbackData, CallJs, &callbackData->tsfn); - // 创建一个异步任务 + // Create an asynchronous task napi_create_async_work(env, nullptr, resourceName, ExecuteWork, WorkComplete, callbackData, &callbackData->work); - // 将异步任务加入到异步队列中,由底层调度执行 + // Add asynchronous tasks to the asynchronous queue and have them executed by the underlying scheduling system napi_queue_async_work(env, callbackData->work); - // 方法返回promise + // Method returns promise napi_value result = nullptr; napi_create_promise(env, &callbackData->deferred, &result); return result; @@ -126,14 +126,14 @@ struct Index { build() { Row() { Column() { - Text('c++异步调用ts') + Text('C++ Asynchronous Call to TS') .fontSize(40) .fontWeight(FontWeight.Bold) .onClick(() => { testNapi.getDisplayWidthAsync().then((res: number) =>{ console.info(`display width = ${res.toString()}`); this.getUIContext().getPromptAction().showToast({ - message: "屏幕宽度:" + res.toString() + message: "screen width:" + res.toString() }) }); }) -- Gitee From b472e7aab93c097df0a90d593652c362d5ee2107 Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:15:44 +0000 Subject: [PATCH 5/9] update NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets. Signed-off-by: birdswu --- .../src/main/ets/pages/IntegrateSOLibrary.ets | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets index 4209c2a..b2a43a6 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets @@ -32,7 +32,7 @@ double sub(double a, double b) // CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(libSub) -#编译源码 +#Compile source code add_library(nativeSub SHARED sub.cpp) // [End LoadThirdSoLibrary1] @@ -87,8 +87,8 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let path = this.context.getHostContext()?.bundleCodeDir; // 获取项目路径 - hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.subSobyDlOpenSo(2, 3, path + '/libs/arm64/libnativeSub.so')); // 传递参数路径信息到Native侧 + let path = this.context.getHostContext()?.bundleCodeDir; // Get project path + hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.subSobyDlOpenSo(2, 3, path + '/libs/arm64/libnativeSub.so')); // Transfer parameter path information to the native side }) } .width('100%') @@ -112,12 +112,12 @@ static napi_value SubSobyDlOpenSo(napi_env env, napi_callback_info info) { napi_get_value_double(env, args[1], &value1); char* path = new char[1024]; size_t size = 1024; - napi_get_value_string_utf8(env, args[2], path, 255, &size); // 获取动态库路径信息 - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path + napi_get_value_string_utf8(env, args[2], path, 255, &size); // Obtain dynamic library path information + void *handle = dlopen(path, RTLD_LAZY); // Open a dynamic link library The path is path napi_value result; - Sub sub_func = (Sub)dlsym(handle, "sub"); // 获取函数名为sub的函数 + Sub sub_func = (Sub)dlsym(handle, "sub"); // Get the function named sub napi_create_double(env, sub_func(value0, value1), &result); - dlclose(handle); // 最后记得close动态库 + dlclose(handle); // Finally, remember to close the dynamic library return result; } // [End LoadThirdSoLibrary5] \ No newline at end of file -- Gitee From 77da51b522e6890efc2ec489b7ea49de63da4eff Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:20:55 +0000 Subject: [PATCH 6/9] update NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets. Signed-off-by: birdswu --- .../MultiSoInterdependenceDecoupling.ets | 42 ++++++++++--------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets index 8daaa16..82131d6 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets @@ -19,20 +19,21 @@ // [Start MultiSoInterdependence1] // a.cpp -extern "C" { // 一定要用extern "C" {}括起来 +extern "C" { // Be sure to enclose it with extern 'C' {} #include "a.h" #include #include "stdio.h" typedef int (*FUNC_SUB)(int, int); int add(int a, int b) { return a + b; } - int getb(char *path, int a, int b) { // path:从ArkTS侧传递So文件的沙箱路径(注意路径要从arkts侧传递、不然有可能找不到路径、具体代码后续会列出) - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path + // Path: The sandbox path for passing So files from ArkTS side (note that the path should be passed from ArkTS side, otherwise it may not be found, and the specific code will be listed later) + int getb(char *path, int a, int b) { + void *handle = dlopen(path, RTLD_LAZY); // Open a dynamic link library The path is path if (!handle) { return 0; } - FUNC_SUB sub_func = (FUNC_SUB)dlsym(handle, "sub"); // 获取函数名为sub的函数 - int res = sub_func(a, b); // 调用函数 - dlclose(handle); // close动态链接库 + FUNC_SUB sub_func = (FUNC_SUB)dlsym(handle, "sub"); // Get the function named sub + int res = sub_func(a, b); // caller function + dlclose(handle); // Close dynamic link library return res; } } @@ -45,20 +46,21 @@ extern "C" { #endif // DemoSO_a_H } // b.cpp -extern "C" { // 一定要用extern "C" {}括起来 +extern "C" { // Be sure to enclose it with extern 'C' {} #include "b.h" #include #include "stdio.h" typedef int (*FUNC_ADD)(int, int); int sub(int a, int b) { return a - b; } - int geta(char *path, int a, int b) { // path:从ArkTS侧传递So文件的沙箱路径(注意路径要从arkts侧传递、不然有可能找不到路径、具体代码后续会列出) - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path + // Path: The sandbox path for passing So files from ArkTS side (note that the path should be passed from ArkTS side, otherwise it may not be found, and the specific code will be listed later) + int geta(char *path, int a, int b) { + void *handle = dlopen(path, RTLD_LAZY); // Open a dynamic link library The path is path if (!handle) { return 0; } - FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // 获取函数名为add的函数 - int res = add_func(a, b); // 调用函数 - dlclose(handle); // close动态链接库 + FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // Get the function named add + int res = add_func(a, b); // caller function + dlclose(handle); // Close dynamic link library return res; } } @@ -73,10 +75,10 @@ extern "C" { // CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) project(liba) -add_library(a SHARED a.cpp) // 编译库liba.so +add_library(a SHARED a.cpp) // Compile library liba.so target_link_libraries(a PUBLIC libace_napi.z.so libhilog_ndk.z.so) project(libb) -add_library(b SHARED b.cpp) // 编译库libb.so +add_library(b SHARED b.cpp) // Compile library libb.so target_link_libraries(b PUBLIC libace_napi.z.so libhilog_ndk.z.so) // [End MultiSoInterdependence1] @@ -87,8 +89,8 @@ project(DemoSO) set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${NATIVERENDER_ROOT_PATH} ${NATIVERENDER_ROOT_PATH}/include) -add_library(demoso SHARED hello.cpp) // 添加libdemoso.so文件 -// 添加依赖库liba.so、libb.so。 注意需要带上路径、不然无法找到对应的so库 +add_library(demoso SHARED hello.cpp) // Add libdemoso. so file +// Add dependency libraries liba.so and libb.so. Please note to include the path, otherwise the corresponding SO library cannot be found target_link_libraries(demoso PUBLIC libace_napi.z.so ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${OHOS_ARCH}/liba.so ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${OHOS_ARCH}/libb.so) // index.ets @@ -108,8 +110,8 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - this.path = this.context.getHostContext()?.bundleCodeDir; // 获取路径 - hilog.info(0x0000, 'testTag', 'Test NAPI 5 + 3 = %{public}d', testNapi.add(5, 3, this.path + '/libs/arm64/liba.so')); // 调用native侧函数 + this.path = this.context.getHostContext()?.bundleCodeDir; // get path + hilog.info(0x0000, 'testTag', 'Test NAPI 5 + 3 = %{public}d', testNapi.add(5, 3, this.path + '/libs/arm64/liba.so')); // Call the native side function hilog.info(0x0000, 'testTag', 'Test NAPI 5 - 3 = %{public}d', testNapi.sub(5, 3, this.path + '/libs/arm64/libb.so')); }) } @@ -146,7 +148,7 @@ static napi_value Add(napi_env env, napi_callback_info info) { char path[255]; size_t size = 255; napi_get_value_string_utf8(env, args[2], path, 255, &size); - int res = geta(path, value0, value1); // 调用函数并传递沙箱路径 + int res = geta(path, value0, value1); // Call the function and pass the sandbox path napi_value sum; napi_create_int32(env, res, &sum); return sum; @@ -169,7 +171,7 @@ static napi_value Sub(napi_env env, napi_callback_info info) { char path[255]; size_t size = 255; napi_get_value_string_utf8(env, args[2], path, 255, &size); - int res = getb(path, value0, value1); // 调用函数并传递沙箱路径 + int res = getb(path, value0, value1); // Call the function and pass the sandbox path napi_value sum; napi_create_int32(env, res, &sum); return sum; -- Gitee From 5c78954c2d2d9fc1dd859c874fe8e7ffd512e24b Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:23:18 +0000 Subject: [PATCH 7/9] update NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets. Signed-off-by: birdswu --- .../src/main/ets/pages/NapiModuleStructure.ets | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets b/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets index 4939f43..78453ce 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets @@ -19,12 +19,12 @@ // [Start NapiModuleStructure] static napi_module demoModule = { - .nm_version = 1, // nm版本号,默认值为1 - .nm_flags = 0, // nm标识符 - .nm_filename = nullptr, // 文件名,暂不关注,使用默认值即可 - .nm_register_func = Init, // 指定nm的入口函数 - .nm_modname = "entry", // 指定ArkTS页面导入的模块名 - .nm_priv = ((void *)0), // 暂不关注,使用默认即可 - .reserved = {0}, // 暂不关注,使用默认值即可 + .nm_version = 1, // nm Version number, default value is 1 + .nm_flags = 0, // nm Identifier + .nm_filename = nullptr, // File name, don't pay attention to it for now, just use the default value + .nm_register_func = Init, // Specify the entrance function for nm + .nm_modname = "entry", // Specify the module name to import from the ArkTS page + .nm_priv = ((void *)0), // Don't follow for now, just use the default settings + .reserved = {0}, // Don't pay attention for now, just use the default value }; // [End NapiModuleStructure] \ No newline at end of file -- Gitee From d9615c1da44e336793b2f29330eefe674a81ba18 Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:24:58 +0000 Subject: [PATCH 8/9] update NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets. Signed-off-by: birdswu --- .../main/ets/pages/NativeSideAccessRawfile.ets | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets index ddd0442..60a7ddd 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets @@ -60,41 +60,41 @@ static napi_value GetRawFileContent(napi_env env, napi_callback_info info) size_t requireArgc = 3; size_t argc = 2; napi_value argv[2] = { nullptr }; - // 获取参数信息 + // Obtain parameter information napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 + // Argv [0] is the first parameter of the function, Js resource object, and OH_ ResourceManagerial is converted to a Native object. NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); size_t strSize; char strBuf[256]; napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); std::string filename(strBuf, strSize); - // 获取rawfile指针对象 + // Get rawfile pointer object RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); if (rawFile != nullptr) { OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "OH_ResourceManager_OpenRawFile success"); } - // 获取rawfile大小并申请内存 + // Get rawfile size and request memory long len = OH_ResourceManager_GetRawFileSize(rawFile); std::unique_ptr data= std::make_unique(len); - // 一次性读取rawfile全部内容 + // Read all contents of rawfile at once int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); - // 关闭打开的指针对象 + // Close open pointer objects OH_ResourceManager_CloseRawFile(rawFile); OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // 转为js对象 + // Convert to JS object return CreateJsArrayValue(env, data, len); } // [End NativeSideAccessRawfile2] // [Start NativeSideAccessRawfile3] -import testNapi from 'libnativeaccessres.so' // 导入so +import testNapi from 'libnativeaccessres.so' // Import so @Entry @Component struct Index { @State message: string = 'Native Access Resource'; context = this.getUIContext(); - private resMgr = this.context.getHostContext()?.resourceManager; // 获取本应用包的资源对象 + private resMgr = this.context.getHostContext()?.resourceManager; // Retrieve the resource objects of this application package build() { Row() { Column() { -- Gitee From c5023a392090177ec6b271a44767693685f798a4 Mon Sep 17 00:00:00 2001 From: birdswu Date: Fri, 16 May 2025 10:26:42 +0000 Subject: [PATCH 9/9] update NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets. Signed-off-by: birdswu --- .../ets/pages/NativeSideCrossModuleAccessR.ets | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets b/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets index d3bf5f0..ed4991e 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets @@ -60,28 +60,28 @@ static napi_value GetRawFileContent(napi_env env, napi_callback_info info) size_t requireArgc = 3; size_t argc = 2; napi_value argv[2] = { nullptr }; - // 获取参数信息 + // Obtain parameter information napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 + // Argv [0] is the first parameter of the function, Js resource object, and OH_ ResourceManagerial is converted to a Native object. NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]); size_t strSize; char strBuf[256]; napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize); std::string filename(strBuf, strSize); - // 获取rawfile指针对象 + // Get rawfile pointer object RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, filename.c_str()); if (rawFile != nullptr) { OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "OH_ResourceManager_OpenRawFile success"); } - // 获取rawfile大小并申请内存 + // Get rawfile size and request memory long len = OH_ResourceManager_GetRawFileSize(rawFile); std::unique_ptr data= std::make_unique(len); - // 一次性读取rawfile全部内容 + // Read all contents of rawfile at once int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); - // 关闭打开的指针对象 + // Close open pointer objects OH_ResourceManager_CloseRawFile(rawFile); OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // 转为js对象 + // Convert to JS object return CreateJsArrayValue(env, data, len); } // [End NativeSideCrossModuleAccessRawfile2] @@ -94,7 +94,7 @@ import testNapi from 'libnativecrossmoduleaccessres.so'; struct Index { @State message: string = 'Native Cross Module Access Resource'; context = this.getUIContext(); - private resMgr = this.context.getHostContext()?.createModuleContext('NativeAccessRes').resourceManager; // 获取本应用包的资源对象 + private resMgr = this.context.getHostContext()?.createModuleContext('NativeAccessRes').resourceManager; // Retrieve the resource objects of this application package build() { Row() { Column() { -- Gitee