From bdc4ef257a1156c1c88a9396e57cfd1fbbe31732 Mon Sep 17 00:00:00 2001 From: CodingGorit Date: Mon, 19 May 2025 17:16:30 +0800 Subject: [PATCH] =?UTF-8?q?faet:=20FAQ=20NDK=20=E6=A0=87=E6=B3=A8=20?= =?UTF-8?q?=E4=B8=8E=20=E4=B8=AD=E6=96=87=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NdkDevelopment/entry/build-profile.json5 | 11 + NdkDevelopment/entry/oh-package-lock.json5 | 39 ++++ NdkDevelopment/entry/oh-package.json5 | 7 +- .../entry/src/main/cpp/CMakeLists.txt | 18 ++ .../src/main/cpp/NapiModuleStructure.cpp | 68 ++++++ .../src/main/cpp/napi_access_rawfile.cpp | 84 ++++++++ .../entry/src/main/cpp/napi_c_open_file.cpp | 82 ++++++++ .../main/cpp/napi_dynamic_load_so_library.cpp | 48 +++++ .../src/main/cpp/napi_get_rawfile_content.cpp | 84 ++++++++ .../entry/src/main/cpp/napi_init.cpp | 83 ++++++++ .../src/main/cpp/napi_init_systemwork.cpp | 57 +++++ .../src/main/cpp/napi_integrate_so_lib.cpp | 42 ++++ .../main/cpp/napi_integrate_so_lib_sub.cpp | 45 ++++ .../src/main/cpp/napi_native_access_res.cpp | 58 ++++++ .../napi_native_call_arkts_async_method.cpp | 114 ++++++++++ .../napi_native_cross_module_access_res.cpp | 57 +++++ .../src/main/cpp/napi_read_arkts_object.cpp | 45 ++++ NdkDevelopment/entry/src/main/cpp/sub.cpp | 6 + NdkDevelopment/entry/src/main/cpp/sub.h | 7 + .../types/libcallsystemasyncwork/Index.d.ts | 3 + .../nativeCallAsyncArkTSMethod.d.ts | 22 ++ .../libcallsystemasyncwork/oh-package.json5 | 6 + .../src/main/cpp/types/libentry/Index.d.ts | 8 + .../types/libentry/nativeReadArkTSObj.d.ts | 23 ++ .../main/cpp/types/libentry/oh-package.json5 | 6 + .../cpp/types/libnativeaccessres/Index.d.ts | 24 +++ .../types/libnativeaccessres/oh-package.json5 | 6 + .../libnativecrossmoduleaccessres/Index.d.ts | 24 +++ .../oh-package.json5 | 6 + .../main/ets/entryability/EntryAbility.ets | 2 + .../pages/AsyncMethodForArkTSFromNative.ets | 106 +--------- .../src/main/ets/pages/CSideOpenFile.ets | 61 +----- .../ets/pages/DynamicallyLoadSOLibrary.ets | 66 +----- .../pages/DynamicallyLoadSOLibraryDirect.ets | 46 ++++ .../ets/pages/GetObjectForArkTSFromNative.ets | 25 ++- .../src/main/ets/pages/IntegrateSOLibrary.ets | 81 +------- .../src/main/ets/pages/IntegrateSoLibrary.txt | 37 ++++ .../pages/IntegrateSoLibraryCMakeConfig.txt | 30 +++ .../MultiSoInterdependenceDecoupling.txt | 196 ++++++++++++++++++ .../ets/pages/NativeSideAccessRawfile.ets | 77 +------ .../pages/NativeSideCrossModuleAccessR.ets | 75 +------ .../pages/NativeSideOperableFileDirectory.ets | 37 +--- .../resources/base/profile/main_pages.json | 3 +- 43 files changed, 1440 insertions(+), 485 deletions(-) create mode 100644 NdkDevelopment/entry/oh-package-lock.json5 create mode 100644 NdkDevelopment/entry/src/main/cpp/CMakeLists.txt create mode 100644 NdkDevelopment/entry/src/main/cpp/NapiModuleStructure.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_access_rawfile.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_c_open_file.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_dynamic_load_so_library.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_get_rawfile_content.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_init.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_init_systemwork.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib_sub.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_native_access_res.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_native_call_arkts_async_method.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_native_cross_module_access_res.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/napi_read_arkts_object.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/sub.cpp create mode 100644 NdkDevelopment/entry/src/main/cpp/sub.h create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/Index.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/oh-package.json5 create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libentry/Index.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libentry/nativeReadArkTSObj.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libentry/oh-package.json5 create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/Index.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/oh-package.json5 create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/Index.d.ts create mode 100644 NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/oh-package.json5 create mode 100644 NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibraryDirect.ets create mode 100644 NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibrary.txt create mode 100644 NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibraryCMakeConfig.txt create mode 100644 NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt diff --git a/NdkDevelopment/entry/build-profile.json5 b/NdkDevelopment/entry/build-profile.json5 index 4d61187..38bdcc9 100644 --- a/NdkDevelopment/entry/build-profile.json5 +++ b/NdkDevelopment/entry/build-profile.json5 @@ -1,6 +1,11 @@ { "apiType": "stageMode", "buildOption": { + "externalNativeOptions": { + "path": "./src/main/cpp/CMakeLists.txt", + "arguments": "", + "cppFlags": "", + } }, "buildOptionSet": [ { @@ -14,6 +19,12 @@ ] } } + }, + "nativeLib": { + "debugSymbol": { + "strip": true, + "exclude": [] + } } }, ], diff --git a/NdkDevelopment/entry/oh-package-lock.json5 b/NdkDevelopment/entry/oh-package-lock.json5 new file mode 100644 index 0000000..2b623f7 --- /dev/null +++ b/NdkDevelopment/entry/oh-package-lock.json5 @@ -0,0 +1,39 @@ +{ + "meta": { + "stableOrder": true + }, + "lockfileVersion": 3, + "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", + "specifiers": { + "libcallsystemasyncwork.so@src/main/cpp/types/libcallsystemasyncwork": "libcallsystemasyncwork.so@src/main/cpp/types/libcallsystemasyncwork", + "libentry.so@src/main/cpp/types/libentry": "libentry.so@src/main/cpp/types/libentry", + "libnativeaccessres.so@src/main/cpp/types/libnativeaccessres": "libnativeaccessres.so@src/main/cpp/types/libnativeaccessres", + "libnativecrossmoduleaccessres.so@src/main/cpp/types/libnativecrossmoduleaccessres": "libnativecrossmoduleaccessres.so@src/main/cpp/types/libnativecrossmoduleaccessres" + }, + "packages": { + "libcallsystemasyncwork.so@src/main/cpp/types/libcallsystemasyncwork": { + "name": "libcallsystemasyncwork.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libcallsystemasyncwork", + "registryType": "local" + }, + "libentry.so@src/main/cpp/types/libentry": { + "name": "libentry.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libentry", + "registryType": "local" + }, + "libnativeaccessres.so@src/main/cpp/types/libnativeaccessres": { + "name": "libnativeaccessres.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libnativeaccessres", + "registryType": "local" + }, + "libnativecrossmoduleaccessres.so@src/main/cpp/types/libnativecrossmoduleaccessres": { + "name": "libnativecrossmoduleaccessres.so", + "version": "1.0.0", + "resolved": "src/main/cpp/types/libnativecrossmoduleaccessres", + "registryType": "local" + } + } +} \ No newline at end of file diff --git a/NdkDevelopment/entry/oh-package.json5 b/NdkDevelopment/entry/oh-package.json5 index 248c3b7..7458994 100644 --- a/NdkDevelopment/entry/oh-package.json5 +++ b/NdkDevelopment/entry/oh-package.json5 @@ -5,6 +5,11 @@ "main": "", "author": "", "license": "", - "dependencies": {} + "dependencies": { + "libentry.so": "file:./src/main/cpp/types/libentry", + "libcallsystemasyncwork.so": "file:./src/main/cpp/types/libcallsystemasyncwork", + "libnativeaccessres.so": "file:./src/main/cpp/types/libnativeaccessres", + "libnativecrossmoduleaccessres.so": "file:./src/main/cpp/types/libnativecrossmoduleaccessres" + } } diff --git a/NdkDevelopment/entry/src/main/cpp/CMakeLists.txt b/NdkDevelopment/entry/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..da17283 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/CMakeLists.txt @@ -0,0 +1,18 @@ +# the minimum version of CMake. +cmake_minimum_required(VERSION 3.5.0) +project(NdkDevlopment) + +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + +if(DEFINED PACKAGE_FIND_FILE) + include(${PACKAGE_FIND_FILE}) +endif() + +include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + +add_library(entry SHARED napi_init.cpp) +add_library(callsystemasyncwork SHARED napi_init_systemwork) +add_library(nativecrossmoduleaccessres SHARED napi_native_cross_module_access_res) +add_library(nativeaccessres SHARED napi_native_access_res) +target_link_libraries(nativeaccessres PUBLIC libace_napi.z.so) \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/NapiModuleStructure.cpp b/NdkDevelopment/entry/src/main/cpp/NapiModuleStructure.cpp new file mode 100644 index 0000000..d5617b8 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/NapiModuleStructure.cpp @@ -0,0 +1,68 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:napi_module结构体字段描述解析 +*/ + +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + +} + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +// [Start napi_module_explain] +static napi_module demoModule = { + .nm_version = 1, // nm version number, default value is 1 + .nm_flags = 0, // nm identifier + .nm_filename = nullptr, // file name, ignore it for the time being, use the default value + .nm_register_func = Init, // Specifies the entrance function of nm + .nm_modname = "entry", // Specify the name of the module to be imported from the ArkTS page + .nm_priv = ((void *)0), // Don't pay attention to it for the time being, use the default one + .reserved = {0}, // Don't pay attention to it for the time being, use the default value +}; +// [End napi_module_explain] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_access_rawfile.cpp b/NdkDevelopment/entry/src/main/cpp/napi_access_rawfile.cpp new file mode 100644 index 0000000..f3f9e63 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_access_rawfile.cpp @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在Native侧跨模块访问资源 +*/ + +// [Start napi_native_side_access_file] +// napi_init.cpp +#include "napi/native_api.h" +#include +#include +#include +#include "hilog/log.h" + +const int GLOBAL_RESMGR = 0xFF00; +const char *TAG = "[Sample_rawfile]"; +namespace { + napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) + { + napi_value buffer; + napi_status status = napi_create_external_arraybuffer( + env, data.get(), length, + [](napi_env env, void *data, void *hint) { + delete[] static_cast(data); + }, + nullptr, &buffer); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create external array buffer"); + return nullptr; + } + napi_value result = nullptr; + status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create media typed array"); + return nullptr; + } + data.release(); + return result; + } +} +static napi_value GetRawFileContent(napi_env env, napi_callback_info info) +{ + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "GetFileContent Begin"); + 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] is the first parameter of the function, the Js resource object, which OH_ResourceManager_InitNativeResourceManager 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); + // Get the rawfile pointer to the elephant + 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"); + } + // Obtain the rawfile size and request memory + long len = OH_ResourceManager_GetRawFileSize(rawFile); + std::unique_ptr data= std::make_unique(len); + // Read the entire contents of the rawfile at once + int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); + // Turn off the open finger icon + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // Convert to a JS object + return CreateJsArrayValue(env, data, len); +} +// [End napi_native_side_access_file] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_c_open_file.cpp b/NdkDevelopment/entry/src/main/cpp/napi_c_open_file.cpp new file mode 100644 index 0000000..5905391 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_c_open_file.cpp @@ -0,0 +1,82 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:C侧如何打开文件 +*/ + +#include "napi/native_api.h" +#include +#define LOG_APP "C_OPEN_FOLE" + +void close(unsigned int fd2) { + +} + +unsigned long read(unsigned int fd, char buffer[4096], unsigned long u) { + +} + +unsigned long write(unsigned int fd2, char * pData1, unsigned long bytesRead) { + +} + +// [Start napi_c_read_file] +static napi_value OpenFile(unsigned int fd, unsigned int fd2) { + OH_LOG_INFO(LOG_APP, "OpenFile"); + + if (fd != -1) { + char buffer[4096]; + ssize_t bytesRead; + // Read the contents of the file into a buffer + bytesRead = read(fd, buffer, sizeof(buffer)); + if (bytesRead == -1) { + OH_LOG_INFO(LOG_APP, "read file failed"); + close(fd); // close file fd + return nullptr; + } + while (bytesRead != 0) { + OH_LOG_INFO(LOG_APP, "read file size %{public}lu", bytesRead); + OH_LOG_INFO(LOG_APP, "read file cg"); + char *pData1 = buffer; + OH_LOG_INFO(LOG_APP, "file contents: \n%{public}s", pData1); + ssize_t bytesWrite; + bytesWrite = write(fd2, pData1, bytesRead); + if (bytesWrite == -1) { + OH_LOG_INFO(LOG_APP, "write file failed"); + close(fd2); // close file fd + return nullptr; + } + bytesRead = read(fd, buffer, sizeof(buffer)); + } + // close file fd + close(fd); + close(fd2); // close file fd + } + return nullptr; +} + +static napi_value ReadFile(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value args[2] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + unsigned int fd = -1; + napi_get_value_uint32(env, args[0], &fd); + unsigned int fd2 = -1; + napi_get_value_uint32(env, args[1], &fd2); + OpenFile(fd, fd2); + return nullptr; +} +// [End napi_c_read_file] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_dynamic_load_so_library.cpp b/NdkDevelopment/entry/src/main/cpp/napi_dynamic_load_so_library.cpp new file mode 100644 index 0000000..f5db071 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_dynamic_load_so_library.cpp @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS侧与Native侧分别如何动态加载SO库 +*/ + +// [Start load_so_library_native_directly] +#include "napi/native_api.h" +#include + typedef double (*FUNC_ADD)(int, int); +static napi_value Add(napi_env env, napi_callback_info info) { + size_t requireArgc = 3; + size_t argc = 3; + napi_value args[3] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + double value0; + napi_get_value_double(env, args[0], &value0); + double value1; + napi_get_value_double(env, args[1], &value1); + char path[255]; + size_t size = 255; + napi_get_value_string_utf8(env, args[2], path, 255, &size); // Obtain the dynamic database path information + void *handle = dlopen(path, RTLD_LAZY); // Open a dynamic link library. The path is path + dlerror(); + FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // Gets the function named add + if (dlerror()) { + return nullptr; + } + double res = add_func(value0, value1); // Call add and pass the parameter information + dlclose(handle); // Finally, remember to close the dynamic library + napi_value sum; + napi_create_double(env, res, &sum); + return sum; +} +// [Start load_so_library_native_directly] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_get_rawfile_content.cpp b/NdkDevelopment/entry/src/main/cpp/napi_get_rawfile_content.cpp new file mode 100644 index 0000000..ce99202 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_get_rawfile_content.cpp @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在Native侧访问应用包内Rawfile资源 +*/ + +// [Start napi_implement_get_rawfile_content] +// napi_init.cpp +#include "napi/native_api.h" +#include +#include +#include +#include "hilog/log.h" + +const int GLOBAL_RESMGR = 0xFF00; +const char *TAG = "[Sample_rawfile]"; +namespace { + napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) + { + napi_value buffer; + napi_status status = napi_create_external_arraybuffer( + env, data.get(), length, + [](napi_env env, void *data, void *hint) { + delete[] static_cast(data); + }, + nullptr, &buffer); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create external array buffer"); + return nullptr; + } + napi_value result = nullptr; + status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); + if (status != napi_ok) { + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create media typed array"); + return nullptr; + } + data.release(); + return result; + } +} +static napi_value GetRawFileContent(napi_env env, napi_callback_info info) +{ + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "GetFileContent Begin"); + 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] is the first parameter of the function, the Js resource object, which OH_ResourceManager_InitNativeResourceManager 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); + // Get the rawfile pointer to the elephant + 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"); + } + // Obtain the rawfile size and request memory + long len = OH_ResourceManager_GetRawFileSize(rawFile); + std::unique_ptr data= std::make_unique(len); + // Read the entire contents of the rawfile at once + int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); + // Turn off the open finger icon + OH_ResourceManager_CloseRawFile(rawFile); + OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); + // Convert to a JS object + return CreateJsArrayValue(env, data, len); +} +// [End napi_implement_get_rawfile_content] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_init.cpp b/NdkDevelopment/entry/src/main/cpp/napi_init.cpp new file mode 100644 index 0000000..44bebbf --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_init.cpp @@ -0,0 +1,83 @@ +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + +} + +static napi_value NAPI_Global_ReadFile(napi_env env, napi_callback_info info) { + // TODO: implements the code; +} +static napi_value NAPI_Global_addByLibPath(napi_env env, napi_callback_info info) { + // TODO: implements the code; +} + +static napi_value NAPI_Global_callFunction(napi_env env, napi_callback_info info) +{ + // TODO: implements the code; +} +static napi_value NAPI_Global_getDisplayWidthAsync(napi_env env, napi_callback_info info) { + // TODO: implements the code; +} +static napi_value NAPI_Global_subSobyDlOpenSo(napi_env env, napi_callback_info info) { + // TODO: implements the code; +} + + + +static napi_value NAPI_Global_getRawFileContent(napi_env env, napi_callback_info info) +{ + // TODO: implements the code; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"ReadFile", nullptr, NAPI_Global_ReadFile, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"addByLibPath", nullptr, NAPI_Global_addByLibPath, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"callFunction", nullptr, NAPI_Global_callFunction, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"getDisplayWidthAsync", nullptr, NAPI_Global_getDisplayWidthAsync, nullptr, nullptr, nullptr, napi_default, + nullptr}, + {"subSobyDlOpenSo", nullptr, NAPI_Global_subSobyDlOpenSo, nullptr, nullptr, nullptr, napi_default, nullptr }, +{ "getRawFileContent", nullptr, NAPI_Global_getRawFileContent, 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); +} diff --git a/NdkDevelopment/entry/src/main/cpp/napi_init_systemwork.cpp b/NdkDevelopment/entry/src/main/cpp/napi_init_systemwork.cpp new file mode 100644 index 0000000..0885e68 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_init_systemwork.cpp @@ -0,0 +1,57 @@ +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + +} + +static napi_value NAPI_Global_getDisplayWidthAsync(napi_env env, napi_callback_info info) { + // TODO: implements the code; +} + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"getDisplayWidthAsync", nullptr, NAPI_Global_getDisplayWidthAsync, 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 = "callsystemasyncwork", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} diff --git a/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib.cpp b/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib.cpp new file mode 100644 index 0000000..185be1f --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib.cpp @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在Native侧如何集成三方SO库 +*/ + +// [Start integrate_so_library_napi_init] +#include "sub.h" +#include "napi/native_api.h" + +static napi_value Sub(napi_env env, napi_callback_info info) +{ + size_t requireArgc = 2; + size_t argc = 2; + napi_value args[2] = {nullptr}; + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + double value0; + napi_get_value_double(env, args[0], &value0); + double value1; + napi_get_value_double(env, args[1], &value1); + napi_value sum; + napi_create_double(env, sub(value0,value1), &sum); + return sum; +} +// [End integrate_so_library_napi_init] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib_sub.cpp b/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib_sub.cpp new file mode 100644 index 0000000..dad4f62 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_integrate_so_lib_sub.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在Native侧如何集成三方SO库 +*/ + +#include "napi/native_api.h" + +// [Start sub_so_by_dio_pen_so] +#include +typedef double (*Sub)(double, double); + +static napi_value SubSobyDlOpenSo(napi_env env, napi_callback_info info) { + size_t requireArgc = 3; + size_t argc = 3; + napi_value args[3] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + double value0; + napi_get_value_double(env, args[0], &value0); + double value1; + 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); Obtain the dynamic database 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"); Get the function whose function name is sub + napi_create_double(env, sub_func(value0, value1), &result); + dlclose(handle); Finally, remember to close the dynamic library + return result; +} +// [End sub_so_by_dio_pen_so] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/napi_native_access_res.cpp b/NdkDevelopment/entry/src/main/cpp/napi_native_access_res.cpp new file mode 100644 index 0000000..af396a1 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_native_access_res.cpp @@ -0,0 +1,58 @@ +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + +} + +static napi_value NAPI_Global_getRawFileContent(napi_env env, napi_callback_info info) +{ + // TODO: implements the code; +} + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + { "getRawFileContent", nullptr, NAPI_Global_getRawFileContent, 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 = "nativeaccessres", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} diff --git a/NdkDevelopment/entry/src/main/cpp/napi_native_call_arkts_async_method.cpp b/NdkDevelopment/entry/src/main/cpp/napi_native_call_arkts_async_method.cpp new file mode 100644 index 0000000..ecbd573 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_native_call_arkts_async_method.cpp @@ -0,0 +1,114 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Native侧如何访问ArkTS侧系统定义的异步方法 +*/ + +// [Start napi_native_call_arkts_async_method] +#include "napi/native_api.h" +#include +#include + +#define LOG_TAG "Pure" // global tag + +// Contextual data, which is used to pass data between threads +struct CallbackData { + napi_threadsafe_function tsfn; + napi_async_work work; + napi_deferred deferred = nullptr; + double res; +}; +static napi_value ResolvedCallback(napi_env env, napi_callback_info info) { + void *data = nullptr; + size_t argc = 1; + napi_value argv[1]; + napi_get_cb_info(env, info, &argc, argv, nullptr, &data); + napi_value widthProp = nullptr; + napi_get_named_property(env, argv[0], "width", &widthProp); + double result = 0; + napi_get_value_double(env, widthProp, &result); + OH_LOG_INFO(LOG_APP, "width in ResolvedCallback is %{public}f", result); + // data is reinterpreted as a pointer to std::p romise, and the value of that 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 the system library module and call the method layer by layer + napi_value systemModule; + napi_load_module(env, "@ohos.display", &systemModule); + napi_value displayFunc = nullptr; + napi_get_named_property(env, systemModule, "getDefaultDisplay", &displayFunc); + napi_value promise = nullptr; + napi_call_function(env, systemModule, displayFunc, 0, nullptr, &promise); + napi_value thenFunc = nullptr; + napi_get_named_property(env, promise, "then", &thenFunc); + napi_value resolvedCallback; + // 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); +} +static void ExecuteWork(napi_env env, void *data) { + CallbackData *callbackData = reinterpret_cast(data); + std::promise promise; + auto future = promise.get_future(); + napi_call_threadsafe_function(callbackData->tsfn, &promise, napi_tsfn_nonblocking); + try { + auto result = future.get(); + callbackData->res = result; + OH_LOG_INFO(LOG_APP, "width in ExecuteWork %{public}f", result); + } catch (const std::exception &e) { + OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", e.what()); + } +} +static void WorkComplete(napi_env env, napi_status status, void *data) { + CallbackData *callbackData = reinterpret_cast(data); + // Send back the service code calculation result to the application + napi_value result = nullptr; + napi_create_double(env, callbackData->res, &result); + napi_resolve_deferred(env, callbackData->deferred, result); + // Release the thread-safe method + 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; +} +static napi_value getDisplayWidthAsync(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value jsCb = nullptr; + CallbackData *callbackData = nullptr; + napi_get_cb_info(env, info, &argc, &jsCb, nullptr, reinterpret_cast(&callbackData)); + + napi_value sysModule; + 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); + // The asynchronous task is added to the asynchronous queue and executed by the underlying scheduler + napi_queue_async_work(env, callbackData->work); + // method returns a promise + napi_value result = nullptr; + napi_create_promise(env, &callbackData->deferred, &result); + return result; +} +// [End napi_native_call_arkts_async_method] diff --git a/NdkDevelopment/entry/src/main/cpp/napi_native_cross_module_access_res.cpp b/NdkDevelopment/entry/src/main/cpp/napi_native_cross_module_access_res.cpp new file mode 100644 index 0000000..8d17252 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_native_cross_module_access_res.cpp @@ -0,0 +1,57 @@ +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + +} + +static napi_value NAPI_Global_getRawFileContent(napi_env env, napi_callback_info info) +{ + // TODO: implements the code; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + { "getRawFileContent", nullptr, NAPI_Global_getRawFileContent, 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 = "nativecrossmoduleaccessres", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} diff --git a/NdkDevelopment/entry/src/main/cpp/napi_read_arkts_object.cpp b/NdkDevelopment/entry/src/main/cpp/napi_read_arkts_object.cpp new file mode 100644 index 0000000..321c843 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_read_arkts_object.cpp @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Native侧如何获取ArkTS侧Object对象及其成员变量 +*/ + +// [Start napi_read_arkts_object] +// Pass in the instance object and call the function in the object on the C side +#include "napi/native_api.h" +static napi_value CallFunction(napi_env env, napi_callback_info info) { + // Get the instance object + size_t argc = 1; + napi_value args[1] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, NULL, NULL); + // A method to get an object + napi_value onCall; + napi_get_named_property(env, args[0], "onCall", &onCall); + // Call a function in an object + napi_value res; + napi_call_function(env, args[0], onCall, 0, nullptr, &res); + return onCall; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"callFunction", nullptr, CallFunction, nullptr, nullptr, nullptr, napi_default, nullptr}}; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +// [StartExclude napi_read_arkts_object] +// [EndExclude napi_read_arkts_object] +// [End napi_read_arkts_object] diff --git a/NdkDevelopment/entry/src/main/cpp/sub.cpp b/NdkDevelopment/entry/src/main/cpp/sub.cpp new file mode 100644 index 0000000..a811d13 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/sub.cpp @@ -0,0 +1,6 @@ +#include +#include "sub.h" +double sub(double a, double b) +{ + return a - b; +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/sub.h b/NdkDevelopment/entry/src/main/cpp/sub.h new file mode 100644 index 0000000..7951ea8 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/sub.h @@ -0,0 +1,7 @@ +#ifndef NDKDEVELOPMENT_SUB_H +#define NDKDEVELOPMENT_SUB_H + +#endif //NDKDEVELOPMENT_SUB_H +extern "C" { + double sub(double a, double b); +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/Index.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/Index.d.ts new file mode 100644 index 0000000..29d018b --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/Index.d.ts @@ -0,0 +1,3 @@ +export const add: (a: number, b: number) => number; + +export const getDisplayWidthAsync: () => Promise; \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts new file mode 100644 index 0000000..7353923 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts @@ -0,0 +1,22 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Native侧如何访问ArkTS侧系统定义的异步方法 +*/ + +// [Start get_display_width_async] +export const getDisplayWidthAsync: () => Promise; +// [End get_display_width_async] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/oh-package.json5 b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/oh-package.json5 new file mode 100644 index 0000000..e39b1ea --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libcallsystemasyncwork.so", + "types": "./Index.d.ts", + "version": "1.0.0", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libentry/Index.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libentry/Index.d.ts new file mode 100644 index 0000000..54d8504 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libentry/Index.d.ts @@ -0,0 +1,8 @@ +export const add: (a: number, b: number) => number; +export const ReadFile: (fd: number, fd1: number) => void; + +export const addByLibPath: (arg0: number, arg1: number, arg2: string) => ESObject; + +export const callFunction: (arg0: object) => void; + +export const subSobyDlOpenSo: (arg0: number, arg1: number, arg2: string) => number; \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libentry/nativeReadArkTSObj.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libentry/nativeReadArkTSObj.d.ts new file mode 100644 index 0000000..a57f612 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libentry/nativeReadArkTSObj.d.ts @@ -0,0 +1,23 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Native侧如何获取ArkTS侧Object对象及其成员变量 +*/ + +// [Start native_call_arkts_object] +// index.d.ts +export const callFunction: (a:object) => void; +// [End native_call_arkts_object] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libentry/oh-package.json5 b/NdkDevelopment/entry/src/main/cpp/types/libentry/oh-package.json5 new file mode 100644 index 0000000..ea41072 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libentry/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libentry.so", + "types": "./Index.d.ts", + "version": "1.0.0", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/Index.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/Index.d.ts new file mode 100644 index 0000000..5a0a8a6 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/Index.d.ts @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在Native侧访问应用包内Rawfile资源 +*/ + +// [Start napi_define_get_rawfile_content_interface] +// src/main/cpp/types/libentry/index.d.ts +import { resourceManager } from "@kit.LocalizationKit"; +export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; +// [End napi_define_get_rawfile_content_interface] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/oh-package.json5 b/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/oh-package.json5 new file mode 100644 index 0000000..494f45f --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libnativeaccessres/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libnativeaccessres.so", + "types": "./Index.d.ts", + "version": "1.0.0", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/Index.d.ts b/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/Index.d.ts new file mode 100644 index 0000000..362e109 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/Index.d.ts @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在Native侧跨模块访问资源 +*/ + +// [Start native_define_get_rawfile_content_interface] +// src/main/cpp/types/libentry/index.d.ts +import { resourceManager } from "@kit.LocalizationKit"; +export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; +// [End native_define_get_rawfile_content_interface] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/oh-package.json5 b/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/oh-package.json5 new file mode 100644 index 0000000..b603e32 --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/types/libnativecrossmoduleaccessres/oh-package.json5 @@ -0,0 +1,6 @@ +{ + "name": "libnativecrossmoduleaccessres.so", + "types": "./Index.d.ts", + "version": "1.0.0", + "description": "Please describe the basic information." +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/entryability/EntryAbility.ets b/NdkDevelopment/entry/src/main/ets/entryability/EntryAbility.ets index 508880a..4625426 100644 --- a/NdkDevelopment/entry/src/main/ets/entryability/EntryAbility.ets +++ b/NdkDevelopment/entry/src/main/ets/entryability/EntryAbility.ets @@ -23,6 +23,8 @@ export default class EntryAbility extends UIAbility { hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); return; } + const context = windowStage.getMainWindowSync().getUIContext(); + AppStorage.setOrCreate("context", context); hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); }); } diff --git a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets index 13fdd5d..2ffafda 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/AsyncMethodForArkTSFromNative.ets @@ -17,107 +17,7 @@ * FAQ:Native侧如何访问ArkTS侧系统定义的异步方法 */ -// [Start AsyncMethodForArkTSFromNative1] -#include "napi/native_api.h" -#include -#include - -#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; - napi_deferred deferred = nullptr; - double res; -}; -static napi_value ResolvedCallback(napi_env env, napi_callback_info info) { - void *data = nullptr; - size_t argc = 1; - napi_value argv[1]; - napi_get_cb_info(env, info, &argc, argv, nullptr, &data); - napi_value widthProp = nullptr; - napi_get_named_property(env, argv[0], "width", &widthProp); - double result = 0; - napi_get_value_double(env, widthProp, &result); - OH_LOG_INFO(LOG_APP, "width in ResolvedCallback is %{public}f", result); - // 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; - napi_get_named_property(env, systemModule, "getDefaultDisplay", &displayFunc); - napi_value promise = nullptr; - napi_call_function(env, systemModule, displayFunc, 0, nullptr, &promise); - napi_value thenFunc = nullptr; - napi_get_named_property(env, promise, "then", &thenFunc); - napi_value resolvedCallback; - // 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); -} -static void ExecuteWork(napi_env env, void *data) { - CallbackData *callbackData = reinterpret_cast(data); - std::promise promise; - auto future = promise.get_future(); - napi_call_threadsafe_function(callbackData->tsfn, &promise, napi_tsfn_nonblocking); - try { - auto result = future.get(); - callbackData->res = result; - OH_LOG_INFO(LOG_APP, "width in ExecuteWork %{public}f", result); - } catch (const std::exception &e) { - OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", e.what()); - } -} -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; -} -static napi_value getDisplayWidthAsync(napi_env env, napi_callback_info info) { - size_t argc = 1; - napi_value jsCb = nullptr; - CallbackData *callbackData = nullptr; - napi_get_cb_info(env, info, &argc, &jsCb, nullptr, reinterpret_cast(&callbackData)); - - napi_value sysModule; - 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); - // Method returns promise - napi_value result = nullptr; - napi_create_promise(env, &callbackData->deferred, &result); - return result; -} -// [End AsyncMethodForArkTSFromNative1] - -// [Start AsyncMethodForArkTSFromNative2] -export const getDisplayWidthAsync: () => Promise; -// [End AsyncMethodForArkTSFromNative2] - -// [Start AsyncMethodForArkTSFromNative3] +// [Start cpp_call_system_async_work] import testNapi from 'libcallsystemasyncwork.so'; @Entry @@ -126,7 +26,7 @@ struct Index { build() { Row() { Column() { - Text('C++ Asynchronous Call to TS') + Text('c++ Asynchronous call TS') .fontSize(40) .fontWeight(FontWeight.Bold) .onClick(() => { @@ -145,4 +45,4 @@ struct Index { .height('100%') } } -// [End AsyncMethodForArkTSFromNative3] \ No newline at end of file +// [End cpp_call_system_async_work] \ 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 f2873b2..dfa9b71 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/CSideOpenFile.ets @@ -17,8 +17,8 @@ * FAQ:C侧如何打开文件 */ -// [Start CSideOpenFile1] -import { fileIo, picker } from '@kit.CoreFileKit'; +// [Start napi_c_open_file] +import { fileIo } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; import testNapi from 'libentry.so'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; @@ -26,12 +26,12 @@ import { photoAccessHelper } from '@kit.MediaLibraryKit'; @Entry @Component struct Index { - @State message: string = '打开文件'; + @State message: string = 'open file'; async open() { const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); - photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE - photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目 + photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // Filter and select the media file type as IMAGE + photoSelectOptions.maxSelectNumber = 5; // Select the maximum number of media files let uris: Array = []; const photoViewPicker = new photoAccessHelper.PhotoViewPicker(); await photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => { @@ -44,7 +44,7 @@ struct Index { let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY); console.info('file fd: ' + file.fd); let fd = file.fd - let filesDir = getContext(this).filesDir; + let filesDir = this.getUIContext().getHostContext()?.filesDir; fileIo.copyFileSync(fd, filesDir + '/test2.jpg') let file2 = fileIo.openSync(filesDir + '/test2.jpg', fileIo.OpenMode.READ_ONLY); let file3 = fileIo.openSync(filesDir + '/test3.jpg', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); @@ -66,51 +66,4 @@ struct Index { .height('100%') } } -// [End CSideOpenFile1] - -// [Start CSideOpenFile2] -static napi_value OpenFile(unsigned int fd, unsigned int fd2) { - OH_LOG_INFO(LOG_APP, "OpenFile"); - - if (fd != -1) { - char buffer[4096]; - ssize_t bytesRead; - // 读取文件内容到缓冲区中 - bytesRead = read(fd, buffer, sizeof(buffer)); - if (bytesRead == -1) { - OH_LOG_INFO(LOG_APP, "读取文件失败"); - close(fd); // 关闭文件描述符 - return nullptr; - } - while (bytesRead != 0) { - OH_LOG_INFO(LOG_APP, "读取文件大小 %{public}lu", bytesRead); - OH_LOG_INFO(LOG_APP, "读取文件cg"); - char *pData1 = buffer; - OH_LOG_INFO(LOG_APP, "文件内容: \n%{public}s", pData1); - ssize_t bytesWrite; - bytesWrite = write(fd2, pData1, bytesRead); - if (bytesWrite == -1) { - OH_LOG_INFO(LOG_APP, "写文件失败"); - close(fd2); // 关闭文件描述符 - return nullptr; - } - bytesRead = read(fd, buffer, sizeof(buffer)); - } - // 关闭文件描述符 - close(fd); - close(fd2); // 关闭文件描述符 - } - return nullptr; -} -static napi_value ReadFile(napi_env env, napi_callback_info info) { - size_t argc = 2; - napi_value args[2] = {nullptr}; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - unsigned int fd = -1; - napi_get_value_uint32(env, args[0], &fd); - unsigned int fd2 = -1; - napi_get_value_uint32(env, args[1], &fd2); - OpenFile(fd, fd2); - return nullptr; -} -// [End CSideOpenFile2] \ No newline at end of file +// [End napi_c_open_file] \ 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 ee3d3a0..d131735 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库 */ -// [Start LoadSoLibrary1] +// [Start lazy_load_so_library_arkts] import { hilog } from '@kit.PerformanceAnalysisKit'; // import testNapi from 'libentry.so'; @@ -33,8 +33,8 @@ struct LoadSoLibrary { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(async() => { - let testNapi = await import("libentry.so") // 加载so库 - hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.default.add(2, 3)); // 通过default调用库函数 + let testNapi = await import("libentry.so") // load so library + hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.default.add(2, 3)); // The library function is called through default // hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3)); }) } @@ -43,62 +43,4 @@ struct LoadSoLibrary { .height('100%') } } -// [End LoadSoLibrary1] - -// [Start LoadSoLibrary2] -import { hilog } from '@kit.PerformanceAnalysisKit'; -import testNapi from 'libentry.so'; - -@Entry -@Component -struct Index { - @State message: string = 'Hello World'; - context = this.getUIContext(); - - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - let path = this.context.getHostContext()?.bundleCodeDir; // 获取项目路径 - hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.addByLibPath(2, 3, path + '/libs/arm64/liba.so')); // 传递参数路径信息到Native侧 - }) - } - .width('100%') - } - .height('100%') - } -} -// [End LoadSoLibrary2] - -// [Start LoadSoLibrary3] -#include "napi/native_api.h" -#include - typedef double (*FUNC_ADD)(int, int); -static napi_value Add(napi_env env, napi_callback_info info) { - size_t requireArgc = 3; - size_t argc = 3; - napi_value args[3] = {nullptr}; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - double value0; - napi_get_value_double(env, args[0], &value0); - double value1; - napi_get_value_double(env, args[1], &value1); - char path[255]; - size_t size = 255; - napi_get_value_string_utf8(env, args[2], path, 255, &size); // 获取动态库路径信息 - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path - dlerror(); - FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); // 获取函数名为add的函数 - if (dlerror()) { - return nullptr; - } - double res = add_func(value0, value1); // 调用add并传递参数信息 - dlclose(handle); // 最后记得close动态库 - napi_value sum; - napi_create_double(env, res, &sum); - return sum; -} -// [End LoadSoLibrary3] \ No newline at end of file +// [End lazy_load_so_library_arkts] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibraryDirect.ets b/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibraryDirect.ets new file mode 100644 index 0000000..1bcbee6 --- /dev/null +++ b/NdkDevelopment/entry/src/main/ets/pages/DynamicallyLoadSOLibraryDirect.ets @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:ArkTS侧与Native侧分别如何动态加载SO库 +*/ + +// [Start load_so_library_directly_arkts] +import { hilog } from '@kit.PerformanceAnalysisKit'; +import testNapi from 'libentry.so'; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + context = this.getUIContext(); + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + let path = this.context.getHostContext()!.bundleCodeDir; // Get the project path + hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.addByLibPath(2, 3, path + '/libs/arm64/liba.so')); // Pass the parameter path information to the Native side + }) + } + .width('100%') + } + .height('100%') + } +} +// [End load_so_library_directly_arkts] \ 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 d70532d..0d2016e 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/GetObjectForArkTSFromNative.ets @@ -17,24 +17,33 @@ * FAQ:Native侧如何获取ArkTS侧Object对象及其成员变量 */ -// [Start GetObjectForArkTSFromNative] +// [Start native_read_arkts_object] // index.ets import testNapi from 'libentry.so'; +const context = AppStorage.get("context") as UIContext; + class A { name:string ='username' onCall() { - this.getUIContext().getPromptAction().showToast({ + context.getPromptAction().showToast({ message:'Message Info', duration:2000 }); console.log("testTag user onCall"); } } -build() { - ... - .onClick(() => { - testNapi.callFunction(new A()); - }) + +@Component +struct NativeReadArkTSObject { + + build() { + // [StartExclude native_read_arkts_object] + // [EndExclude native_read_arkts_object] + Button("readArkTSObject") + .onClick(() => { + testNapi.callFunction(new A()); + }) + } } -// [End GetObjectForArkTSFromNative] \ No newline at end of file +// [End native_read_arkts_object] \ 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 b2a43a6..0da2504 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSOLibrary.ets @@ -17,60 +17,7 @@ * FAQ:在Native侧如何集成三方SO库 */ -// [Start LoadThirdSoLibrary1] -// sub.h -extern "C" { - double sub(double a, double b); -} -// sub.cpp -#include -#include "sub.h" -double sub(double a, double b) -{ - return a - b; -} -// CMakeLists.txt -cmake_minimum_required(VERSION 3.4.1) -project(libSub) -#Compile source code -add_library(nativeSub SHARED sub.cpp) -// [End LoadThirdSoLibrary1] - -// [Start LoadThirdSoLibrary2] -# CMakeLists.txt -cmake_minimum_required(VERSION 3.4.1) -project(hello) -set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) -include_directories(${NATIVERENDER_ROOT_PATH} -${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) -// [End LoadThirdSoLibrary2] - -// [Start LoadThirdSoLibrary3] -#include "sub.h" -static napi_value Sub(napi_env env, napi_callback_info info) -{ - size_t requireArgc = 2; - size_t argc = 2; - napi_value args[2] = {nullptr}; - napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); - napi_valuetype valuetype0; - napi_typeof(env, args[0], &valuetype0); - napi_valuetype valuetype1; - napi_typeof(env, args[1], &valuetype1); - double value0; - napi_get_value_double(env, args[0], &value0); - double value1; - napi_get_value_double(env, args[1], &value1); - napi_value sum; - napi_create_double(env, sub(value0 - value1), &sum); - return sum; -} -// [End LoadThirdSoLibrary3] - -// [Start LoadThirdSoLibrary4] +// [Start napi_integrate_so_library] import { hilog } from '@kit.PerformanceAnalysisKit'; import testNapi from 'libentry.so'; @@ -96,28 +43,4 @@ struct Index { .height('100%') } } -// [End LoadThirdSoLibrary4] - -// [Start LoadThirdSoLibrary5] -#include - typedef double (*Sub)(double, double); -static napi_value SubSobyDlOpenSo(napi_env env, napi_callback_info info) { - size_t requireArgc = 3; - size_t argc = 3; - napi_value args[3] = {nullptr}; - napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); - double value0; - napi_get_value_double(env, args[0], &value0); - double value1; - 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); // 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"); // Get the function named sub - napi_create_double(env, sub_func(value0, value1), &result); - dlclose(handle); // Finally, remember to close the dynamic library - return result; -} -// [End LoadThirdSoLibrary5] \ No newline at end of file +// [End napi_integrate_so_library] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibrary.txt b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibrary.txt new file mode 100644 index 0000000..e800836 --- /dev/null +++ b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibrary.txt @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在Native侧如何集成三方SO库 +*/ + +// [Start integrate_so_library_one] +// sub.h +extern "C" { + double sub(double a, double b); +} +// sub.cpp +#include +#include "sub.h" +double sub(double a, double b) +{ + return a - b; +} +// CMakeLists.txt +cmake_minimum_required(VERSION 3.4.1) +project(libSub) +#build source code +add_library(nativeSub SHARED sub.cpp) +// [Start integrate_so_library_one] \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibraryCMakeConfig.txt b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibraryCMakeConfig.txt new file mode 100644 index 0000000..4b657c8 --- /dev/null +++ b/NdkDevelopment/entry/src/main/ets/pages/IntegrateSoLibraryCMakeConfig.txt @@ -0,0 +1,30 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在Native侧如何集成三方SO库 +*/ + +// [Start integrate_so_library_cmake_config] +# CMakeLists.txt +cmake_minimum_required(VERSION 3.4.1) +project(hello) +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(${NATIVERENDER_ROOT_PATH} +${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) +// [Start integrate_so_library_cmake_config] diff --git a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt new file mode 100644 index 0000000..8bf2f74 --- /dev/null +++ b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt @@ -0,0 +1,196 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:多so相互依赖场景下如何解耦 +*/ + +// [Start multi_so_extract_one] +// a.cpp +extern "C" { // Get the project path must be enclosed 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: the sandbox path of the So file passed from the ArkTS side (note that the path should be passed from the arkts side, otherwise the path may not be found, and the specific code will be listed later) + 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"); Get the function whose function name is sub + int res = sub_func(a, b); Call the function + dlclose(handle); closeDynamic link library + return res; + } +} +// a.h +extern "C" { + #ifndef DemoSO_a_H + #define DemoSO_a_H + int add(int a, int b); + int getb(char *path, int a, int b); + #endif // DemoSO_a_H +} +// b.cpp +extern "C" { // Get the project path must be enclosed 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: the sandbox path of the So file passed from the ArkTS side (note that the path should be passed from the arkts side, otherwise the path may not be found, and the specific code will be listed later) + void *handle = dlopen(path, RTLD_LAZY); // opens a dynamic link library. The path is path + if (!handle) { + return 0; + } + FUNC_ADD add_func = (FUNC_ADD)dlsym(handle, "add"); Gets the function named add + int res = add_func(a, b); Call the function + dlclose(handle); closeDynamic link library + return res; + } +} +// b.h +extern "C" { + #ifndef DemoSO_b_H + #define DemoSO_b_H + int sub(int a, int b); + int geta(char *path, int a, int b); + #endif // DemoSO_b_H +} +// CMakeLists.txt +cmake_minimum_required(VERSION 3.4.1) +project(liba) +add_library(a SHARED a.cpp) // build liba.so +target_link_libraries(a PUBLIC libace_napi.z.so libhilog_ndk.z.so) +project(libb) +add_library(b SHARED b.cpp) // build libb.so +target_link_libraries(b PUBLIC libace_napi.z.so libhilog_ndk.z.so) +// [End multi_so_extract_one] + +// [Start multi_so_extract_two] +// CMakeLists.txt +cmake_minimum_required(VERSION 3.4.1) +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) // add libdemoso.so +Add dependencies liba.so, libb.so. Note that you need to bring the path, otherwise you will not be able to find the corresponding so library +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 +import { hilog } from '@kit.LancetKit'; +import testNapi from 'libdemoso.so'; +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + private path: string = ''; + context = this.getUIContext(); + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + this.path = this.context.getHostContext()?.bundleCodeDir; // Get the path + hilog.info(0x0000, 'testTag', 'Test NAPI 5 + 3 = %{public}d', testNapi.add(5, 3, this.path + '/libs/arm64/liba.so')); // call native function + hilog.info(0x0000, 'testTag', 'Test NAPI 5 - 3 = %{public}d', testNapi.sub(5, 3, this.path + '/libs/arm64/libb.so')); + }) + } + .width('100%') + } + .height('100%') + } +} + +// index.d.ts +export const add: (a: number, b: number, path: string) => number; +export const sub: (a: number, b: number, path: string) => number; + +// hello.cpp +#include "a.h" +#include "b.h" +#include "napi/native_api.h" + +static napi_value Add(napi_env env, napi_callback_info info) { + size_t requireArgc = 3; + size_t argc = 3; + napi_value args[3] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + napi_valuetype valuetype2; + napi_typeof(env, args[2], &valuetype2); + int value0; + napi_get_value_int32(env, args[0], &value0); + int value1; + napi_get_value_int32(env, args[1], &value1); + char path[255]; + size_t size = 255; + napi_get_value_string_utf8(env, args[2], path, 255, &size); + 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; +} +static napi_value Sub(napi_env env, napi_callback_info info) { + size_t requireArgc = 3; + size_t argc = 3; + napi_value args[3] = {nullptr}; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + napi_valuetype valuetype2; + napi_typeof(env, args[2], &valuetype2); + int value0; + napi_get_value_int32(env, args[0], &value0); + int value1; + napi_get_value_int32(env, args[1], &value1); + char path[255]; + size_t size = 255; + napi_get_value_string_utf8(env, args[2], path, 255, &size); + 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; +} +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = {{"add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"sub", nullptr, Sub, 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 = "demoso", + .nm_priv = ((void *)0), + .reserved = {0}, +}; +extern "C" __attribute__((constructor)) void RegisterDemosoModule(void) { napi_module_register(&demoModule); } +// [Start multi_so_extract_two] \ 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 60a7ddd..65462a7 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets @@ -17,84 +17,15 @@ * FAQ:如何在Native侧访问应用包内Rawfile资源 */ -// [Start NativeSideAccessRawfile1] -import { resourceManager } from "@kit.LocalizationKit"; -export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// [End NativeSideAccessRawfile1] - -// [Start NativeSideAccessRawfile2] -#include "napi/native_api.h" -#include -#include -#include "hilog/log.h" - -const int GLOBAL_RESMGR = 0xFF00; -const char *TAG = "[Sample_rawfile]"; -namespace { - napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) - { - napi_value buffer; - napi_status status = napi_create_external_arraybuffer( - env, data.get(), length, - [](napi_env env, void *data, void *hint) { - delete[] static_cast(data); - }, - nullptr, &buffer); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create external array buffer"); - return nullptr; - } - napi_value result = nullptr; - status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create media typed array"); - return nullptr; - } - data.release(); - return result; - } -} -static napi_value GetRawFileContent(napi_env env, napi_callback_info info) -{ - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "GetFileContent Begin"); - 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] 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); - // 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"); - } - // Get rawfile size and request memory - long len = OH_ResourceManager_GetRawFileSize(rawFile); - std::unique_ptr data= std::make_unique(len); - // 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); - // Convert to JS object - return CreateJsArrayValue(env, data, len); -} -// [End NativeSideAccessRawfile2] - -// [Start NativeSideAccessRawfile3] -import testNapi from 'libnativeaccessres.so' // Import so +// [Start call_napi_get_rawfile_content] +import testNapi from 'libnativeaccessres.so' // import so lib @Entry @Component struct Index { @State message: string = 'Native Access Resource'; context = this.getUIContext(); - private resMgr = this.context.getHostContext()?.resourceManager; // Retrieve the resource objects of this application package + private resMgr = this.context.getHostContext()?.resourceManager; // Obtain the resource object of this application package build() { Row() { Column() { @@ -111,4 +42,4 @@ struct Index { .height('100%') } } -// [End NativeSideAccessRawfile3] \ No newline at end of file +// [End call_napi_get_rawfile_content] \ 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 ed4991e..d85f81c 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideCrossModuleAccessR.ets @@ -17,76 +17,7 @@ * FAQ:如何在Native侧跨模块访问资源 */ -// [Start NativeSideCrossModuleAccessRawfile1] -import { resourceManager } from "@kit.LocalizationKit"; -export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// [End NativeSideCrossModuleAccessRawfile1] - -// [Start NativeSideCrossModuleAccessRawfile2] -#include "napi/native_api.h" -#include -#include -#include "hilog/log.h" - -const int GLOBAL_RESMGR = 0xFF00; -const char *TAG = "[Sample_rawfile]"; -namespace { - napi_value CreateJsArrayValue(napi_env env, std::unique_ptr &data, long length) - { - napi_value buffer; - napi_status status = napi_create_external_arraybuffer( - env, data.get(), length, - [](napi_env env, void *data, void *hint) { - delete[] static_cast(data); - }, - nullptr, &buffer); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create external array buffer"); - return nullptr; - } - napi_value result = nullptr; - status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result); - if (status != napi_ok) { - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "Failed to create media typed array"); - return nullptr; - } - data.release(); - return result; - } -} -static napi_value GetRawFileContent(napi_env env, napi_callback_info info) -{ - OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "GetFileContent Begin"); - 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] 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); - // 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"); - } - // Get rawfile size and request memory - long len = OH_ResourceManager_GetRawFileSize(rawFile); - std::unique_ptr data= std::make_unique(len); - // 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); - // Convert to JS object - return CreateJsArrayValue(env, data, len); -} -// [End NativeSideCrossModuleAccessRawfile2] - -// [Start NativeSideCrossModuleAccessRawfile3] +// [Start native_side_access_file] import testNapi from 'libnativecrossmoduleaccessres.so'; @Entry @@ -94,7 +25,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; // Retrieve the resource objects of this application package + private resMgr = this.context.getHostContext()?.resourceManager // Obtain the resource object of this application package build() { Row() { Column() { @@ -111,4 +42,4 @@ struct Index { .height('100%') } } -// [End NativeSideCrossModuleAccessRawfile3] \ No newline at end of file +// [End native_side_access_file] \ 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 39a66bb..d23a157 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets @@ -17,37 +17,10 @@ * FAQ:Native侧如何获取可操作的文件目录 */ -// [Start NativeSideOperableFileDirectory] +// [Start native_get_operable_file_dir] import { common } from '@kit.AbilityKit'; -// [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 +const context = AppStorage.get("context") as UIContext; +let hostContext = context.getHostContext() as common.UIAbilityContext; +let filesDir = hostContext.filesDir; +// [End native_get_operable_file_dir] \ 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 55c3f00..09ab5f8 100644 --- a/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json +++ b/NdkDevelopment/entry/src/main/resources/base/profile/main_pages.json @@ -1,5 +1,6 @@ { "src": [ - "pages/Index" + "pages/Index", + "pages/CSideOpenFile" ] } \ No newline at end of file -- Gitee