diff --git a/NdkDevelopment/entry/build-profile.json5 b/NdkDevelopment/entry/build-profile.json5 index 4d611879c7913fb0610c686e2399258ab3a6dad1..38bdcc9929e2c5bd7f51c4fc96a398ccebd0d6ce 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 0000000000000000000000000000000000000000..2b623f7d3135e3932c2fdd26acc8c1e8b4c8834c --- /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 248c3b7541a589682a250f86a6d3ecf7414d2d6a..7458994f7102cf9d418ae44e22182642ebc5ad1c 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 0000000000000000000000000000000000000000..da172834d9a1d99665d0bad19b44e2a7db112fb9 --- /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 0000000000000000000000000000000000000000..d5617b826ecb52bd4686f50e3d107177e426d94d --- /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 0000000000000000000000000000000000000000..f3f9e63cc9ce52ab6e4df228776177f5ca84465f --- /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 0000000000000000000000000000000000000000..590539199f944c6604995f09e95cd1cbf6c0a999 --- /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 0000000000000000000000000000000000000000..f5db071e93a32c82f77bb5bce7bca038407139d7 --- /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 0000000000000000000000000000000000000000..ce9920202d7139852a451797397f838e1a7d81ff --- /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 0000000000000000000000000000000000000000..44bebbfb828bb7bbbb43a002ef8feaf92ab98103 --- /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 0000000000000000000000000000000000000000..0885e68c2b59ad44852caf80ad23a467b01187ec --- /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 0000000000000000000000000000000000000000..185be1f3d2ddfa7a1a2b24615415cd5e964b392b --- /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 0000000000000000000000000000000000000000..dad4f62ecf4e402f69668221ffaf963f15444f18 --- /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 0000000000000000000000000000000000000000..af396a179ae90b5c24e6d4182ae23f489ac1e795 --- /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 0000000000000000000000000000000000000000..ecbd573430049b7a4c5549282a9fe2f19f84bd4d --- /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 0000000000000000000000000000000000000000..8d172523a7b7b5e9a9cc7081a8c9a95570bd5167 --- /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 0000000000000000000000000000000000000000..dbd0005736cf8f9874899a7f6eff124c0160342e --- /dev/null +++ b/NdkDevelopment/entry/src/main/cpp/napi_read_arkts_object.cpp @@ -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: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] +} \ No newline at end of file diff --git a/NdkDevelopment/entry/src/main/cpp/sub.cpp b/NdkDevelopment/entry/src/main/cpp/sub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a811d13fc2194e6cfad5f5874f2e6223d6129a69 --- /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 0000000000000000000000000000000000000000..7951ea88971ad1ace66eabf527a3994f80940285 --- /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 0000000000000000000000000000000000000000..29d018bd6343994e648b15b1240f442c4cc7d8ec --- /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/ets/pages/NapiModuleStructure.ets b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts similarity index 50% rename from NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets rename to NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts index d673717bae15cb0be6e6b187a9600ecc2d22744a..735392319d75d9c64ae55e5ccc4acbe2de0f2028 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NapiModuleStructure.ets +++ b/NdkDevelopment/entry/src/main/cpp/types/libcallsystemasyncwork/nativeCallAsyncArkTSMethod.d.ts @@ -14,17 +14,9 @@ */ /* -* FAQ:napi_module结构体字段描述解析 +* FAQ:Native侧如何访问ArkTS侧系统定义的异步方法 */ -// DocsCode 1 -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}, // 暂不关注,使用默认值即可 -}; -// DocsCode 1 \ No newline at end of file +// [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 0000000000000000000000000000000000000000..e39b1ea184e79c9849b40f7aec8042bfd74cc2c4 --- /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 0000000000000000000000000000000000000000..54d8504161c599142ad3fc0489cd6a2cbd864fb0 --- /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 0000000000000000000000000000000000000000..a57f6123b81671c74fdd98445a739dc946c45ccb --- /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 0000000000000000000000000000000000000000..ea410725a8826704d061021d98cf02aa76cd8016 --- /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 0000000000000000000000000000000000000000..5a0a8a67cac1b166d4516f6d1874c03b72e499cf --- /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 0000000000000000000000000000000000000000..494f45f12e4e0dc80c22378f311edd4b6ffa132f --- /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 0000000000000000000000000000000000000000..362e109342129e74d5cdeddeed10b70e1147d4e8 --- /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 0000000000000000000000000000000000000000..b603e32c889c9f407b3ee530652053dd61fe5559 --- /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 508880af8c33aa838016d1cd4b2c68be2f447540..4625426c773bf444908c44929489f82d5e8266c4 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 c9aa22b7aa35d527691d06745469fffcdc39ef29..2ffafda771af3f028dc4f57bd0d029e2545e06a9 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侧系统定义的异步方法 */ -// DocsCode 1 -#include "napi/native_api.h" -#include -#include - -#define LOG_TAG "Pure" // 全局tag宏,标识模块日志tag - -// 上下文数据,用于线程间传递数据 -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被重新解释为指向std::promise的指针,并设置该promise的值为width - reinterpret_cast *>(data)->set_value(result); - return nullptr; -} -static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) { - // 导入系统库模块,逐层向下调用到方法 - 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回调 - 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); - // 回传业务代码计算结果给应用 - napi_value result = nullptr; - napi_create_double(env, callbackData->res, &result); - napi_resolve_deferred(env, callbackData->deferred, result); - // 释放线程安全方法 - napi_release_threadsafe_function(callbackData->tsfn, napi_tsfn_release); - // 删除异步工作项 - 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); - // 创建一个线程安全函数 - 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); - // 创建一个异步任务 - napi_create_async_work(env, nullptr, resourceName, ExecuteWork, WorkComplete, callbackData, &callbackData->work); - // 将异步任务加入到异步队列中,由底层调度执行 - napi_queue_async_work(env, callbackData->work); - // 方法返回promise - napi_value result = nullptr; - napi_create_promise(env, &callbackData->deferred, &result); - return result; -} -// DocsCode 1 - -// DocsCode 2 -export const getDisplayWidthAsync: () => Promise; -// DocsCode 2 - -// DocsCode 3 +// [Start cpp_call_system_async_work] import testNapi from 'libcallsystemasyncwork.so'; @Entry @@ -126,14 +26,14 @@ struct Index { build() { Row() { Column() { - Text('c++异步调用ts') + Text('c++ Asynchronous call 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() }) }); }) @@ -145,4 +45,4 @@ struct Index { .height('100%') } } -// DocsCode 3 \ 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 5d9791448e9fa2773a5222a1ee2ff7e680e51e76..dfa9b719c9ec758f75c6930439758ce97b71e447 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侧如何打开文件 */ -// DocsCode 1 -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%') } } -// DocsCode 1 - -// DocsCode 2 -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; -} -// DocsCode 2 \ 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 3163a1979ae35e8b8b13651ec37c947d0ecd22a3..d1317358fa33dedc45127c1b73cac4cc63cf5ae4 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 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%') } } -// DocsCode 1 - -// DocsCode 2 -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%') - } -} -// DocsCode 2 - -// DocsCode 3 -#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; -} -// DocsCode 3 \ 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 0000000000000000000000000000000000000000..1bcbee6ed2de57016a540d45d0b035c59bc21528 --- /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 bb1609a576814d5848562f92875ea36c699a33f3..106896c42768376642a74e63ff193450102b074e 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对象及其成员变量 */ -// DocsCode 1 +// [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()); + }) + } } -// DocsCode 1 \ 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 18254a414d6937080eacd4e33812a57d5a30a0a7..af98d6b94a4c37fd2c6ee3ebdb2c8e16fb0cdb92 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库 */ -// DocsCode 1 -// 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) -#编译源码 -add_library(nativeSub SHARED sub.cpp) -// DocsCode 1 - -// DocsCode 2 -# 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) -// DocsCode 2 - -// DocsCode 3 -#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; -} -// DocsCode 3 - -// DocsCode 4 +// [Start napi_integrate_so_library] import { hilog } from '@kit.PerformanceAnalysisKit'; import testNapi from 'libentry.so'; @@ -87,7 +34,7 @@ struct Index { .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { - let path = this.context.getHostContext()?.bundleCodeDir; // 获取项目路径 + let path = this.context.getHostContext()?.bundleCodeDir; // Get the project path hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.subSobyDlOpenSo(2, 3, path + '/libs/arm64/libnativeSub.so')); // 传递参数路径信息到Native侧 }) } @@ -96,28 +43,4 @@ struct Index { .height('100%') } } -// DocsCode 4 - -// DocsCode 5 -#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); // 获取动态库路径信息 - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path - napi_value result; - Sub sub_func = (Sub)dlsym(handle, "sub"); // 获取函数名为sub的函数 - napi_create_double(env, sub_func(value0, value1), &result); - dlclose(handle); // 最后记得close动态库 - return result; -} -// DocsCode 5 \ 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 0000000000000000000000000000000000000000..e80083628f1821c0e8db2a88317479338bc5dc60 --- /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 0000000000000000000000000000000000000000..4b657c818d6d49f261c65bf350a5e0e31f12a03b --- /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.ets b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt similarity index 72% rename from NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets rename to NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt index 508eb056d64edb11f30a2a421bd6754bbe029cf7..8bf2f74a07d49e18229fd101648fcd634abf3cf7 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/MultiSoInterdependenceDecoupling.txt @@ -17,22 +17,22 @@ * FAQ:多so相互依赖场景下如何解耦 */ -// DocsCode 1 +// [Start multi_so_extract_one] // a.cpp -extern "C" { // 一定要用extern "C" {}括起来 +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:从ArkTS侧传递So文件的沙箱路径(注意路径要从arkts侧传递、不然有可能找不到路径、具体代码后续会列出) - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path + 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"); // 获取函数名为sub的函数 - int res = sub_func(a, b); // 调用函数 - dlclose(handle); // close动态链接库 + 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; } } @@ -45,20 +45,20 @@ extern "C" { #endif // DemoSO_a_H } // b.cpp -extern "C" { // 一定要用extern "C" {}括起来 +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:从ArkTS侧传递So文件的沙箱路径(注意路径要从arkts侧传递、不然有可能找不到路径、具体代码后续会列出) - void *handle = dlopen(path, RTLD_LAZY); // 打开一个动态链接库.路径为path + 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"); // 获取函数名为add的函数 - int res = add_func(a, b); // 调用函数 - dlclose(handle); // close动态链接库 + 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; } } @@ -73,22 +73,22 @@ 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) // build 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) // build libb.so target_link_libraries(b PUBLIC libace_napi.z.so libhilog_ndk.z.so) -// DocsCode 1 +// [End multi_so_extract_one] -// DocsCode 2 +// [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) // 添加libdemoso.so文件 -// 添加依赖库liba.so、libb.so。 注意需要带上路径、不然无法找到对应的so库 +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 @@ -108,8 +108,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 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')); }) } @@ -146,7 +146,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 +169,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; @@ -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 +// [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 1d674bc22d392d1174b3418dbf7112681bf9ac99..8a2031d8139ccade501b5abe2a6bf8cbf4eabf72 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideAccessRawfile.ets @@ -17,76 +17,7 @@ * FAQ:如何在Native侧访问应用包内Rawfile资源 */ -// DocsCode 1 -import { resourceManager } from "@kit.LocalizationKit"; -export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// DocsCode 1 - -// DocsCode 2 -#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 }; - // 获取参数信息 - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 - 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指针对象 - 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大小并申请内存 - long len = OH_ResourceManager_GetRawFileSize(rawFile); - std::unique_ptr data= std::make_unique(len); - // 一次性读取rawfile全部内容 - int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); - // 关闭打开的指针对象 - OH_ResourceManager_CloseRawFile(rawFile); - OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // 转为js对象 - return CreateJsArrayValue(env, data, len); -} -// DocsCode 2 - -// DocsCode 3 +// [Start call_napi_get_rawfile_content] import testNapi from 'libnativeaccessres.so' // 导入so @Entry @@ -94,7 +25,7 @@ import testNapi from 'libnativeaccessres.so' // 导入so struct Index { @State message: string = 'Native Access Resource'; context = this.getUIContext(); - private resMgr = this.context.getHostContext()?.resourceManager; // 获取本应用包的资源对象 + 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%') } } -// DocsCode 3 \ 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 91c20a994586fe91d5b332ef9ddab6a2da7d9c12..d85f81c74efc591467859e1fd73e6c912646bbc0 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侧跨模块访问资源 */ -// DocsCode 1 -import { resourceManager } from "@kit.LocalizationKit"; -export const getRawFileContent: (resMgr: resourceManager.ResourceManager, path: string) => Uint8Array; -// DocsCode 1 - -// DocsCode 2 -#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 }; - // 获取参数信息 - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); - // argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。 - 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指针对象 - 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大小并申请内存 - long len = OH_ResourceManager_GetRawFileSize(rawFile); - std::unique_ptr data= std::make_unique(len); - // 一次性读取rawfile全部内容 - int res = OH_ResourceManager_ReadRawFile(rawFile, data.get(), len); - // 关闭打开的指针对象 - OH_ResourceManager_CloseRawFile(rawFile); - OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr); - // 转为js对象 - return CreateJsArrayValue(env, data, len); -} -// DocsCode 2 - -// DocsCode 3 +// [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; // 获取本应用包的资源对象 + 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%') } } -// DocsCode 3 \ 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 4fb3f430f6ecadd52e1a002e02e464eac7b27477..d23a1573d0681f7f1a593683f97c0ec44b971527 100644 --- a/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets +++ b/NdkDevelopment/entry/src/main/ets/pages/NativeSideOperableFileDirectory.ets @@ -17,10 +17,10 @@ * FAQ:Native侧如何获取可操作的文件目录 */ -// DocsCode 1 +// [Start native_get_operable_file_dir] import { common } from '@kit.AbilityKit'; -context = this.getUIContext(); -let hostContext = this.context.getHostContext() as common.UIAbilityContext; +const context = AppStorage.get("context") as UIContext; +let hostContext = context.getHostContext() as common.UIAbilityContext; let filesDir = hostContext.filesDir; -// DocsCode 1 \ No newline at end of file +// [End native_get_operable_file_dir] \ No newline at end of file