From 84b7911822205761ecb0efd06767c157bb010d8d Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 09:40:56 +0800 Subject: [PATCH 1/6] add cJson_Parse func Signed-off-by: gou-jingjing --- .../entry/src/main/cpp/CMakeLists.txt | 1 + .../entry/src/main/cpp/include/nodeapi.h | 1 + .../napitutorials/entry/src/main/cpp/init.cpp | 3 +- .../cpp/ncpp/cjsoncase/cjsonparsecase.cpp | 303 ++++++++++++++++++ .../src/main/cpp/types/libentry/index.d.ts | 12 + .../src/ohosTest/ets/test/Ability.test.ets | 19 ++ .../tool/commandLine/src/function.json | 31 +- .../commandLine/src/napiGen/functionDirect.js | 146 +++++++-- .../src/napiGen/functionDirectTest.js | 16 +- .../tool/commandLine/src/tsGen/tsMain.js | 176 ++++++++-- 10 files changed, 630 insertions(+), 78 deletions(-) create mode 100644 examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp diff --git a/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt b/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt index 9608fe94..7e38fc16 100644 --- a/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt +++ b/examples/napitutorials/entry/src/main/cpp/CMakeLists.txt @@ -21,6 +21,7 @@ add_library(entry SHARED nodeapi/datatypes/napithreadsafefuncall.cpp nodeapi/datatypes/napiextendederrorinfo.cpp ncpp/cjsoncase/cjsoncase.cpp + ncpp/cjsoncase/cjsonparsecase.cpp javascriptapi/jsproperty/napigetpropertynames.cpp javascriptapi/jsproperty/napigetproperty.cpp javascriptapi/jsproperty/napisetproperty.cpp diff --git a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h index d267dff9..9e470419 100644 --- a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h +++ b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h @@ -32,5 +32,6 @@ napi_value setThreadsafefuncrel(napi_env env, napi_callback_info info); napi_value setThreadsafefuncall(napi_env env, napi_callback_info info); napi_value cJSONVersion(napi_env env, napi_callback_info info); +napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info); #endif //NAPITUTORIALS_NODEAPI_H diff --git a/examples/napitutorials/entry/src/main/cpp/init.cpp b/examples/napitutorials/entry/src/main/cpp/init.cpp index 996ec015..9f03a760 100644 --- a/examples/napitutorials/entry/src/main/cpp/init.cpp +++ b/examples/napitutorials/entry/src/main/cpp/init.cpp @@ -67,7 +67,8 @@ static napi_value Init(napi_env env, napi_value exports) {"testNapiThreadsafefuncall", nullptr, setThreadsafefuncall, nullptr, nullptr, nullptr, napi_default, nullptr}, {"cjson_version", nullptr, cJSONVersion, nullptr, nullptr, nullptr, napi_default, nullptr}, {"getContext", nullptr, NativeXComponentSample::PluginManager::GetContext, - nullptr, nullptr, nullptr, napi_default, nullptr} + nullptr, nullptr, nullptr, napi_default, nullptr}, + {"KH418_cJSON_Parse", nullptr, KH418_CJSON_Parse, nullptr, nullptr, nullptr, napi_default, nullptr}, }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp new file mode 100644 index 00000000..0a3b53b8 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp @@ -0,0 +1,303 @@ +#include "cjson/cJSON.h" +#include "napi/native_api.h" +#include +#include +#include + +#define GLOBAL_RESMGR (0xFFEE) +constexpr int32_t STR_MAX_SIZE = 200; +constexpr int32_t LONG_STR_MAX_SIZE = 1024; +constexpr int32_t ERR_OK = 0; +constexpr int8_t NO_ERROR = 0; +constexpr int8_t ERROR = -1; +constexpr uint8_t PARAM0 = 0; +constexpr uint8_t PARAM1 = 1; +constexpr uint8_t PARAM2 = 2; +constexpr uint8_t PARAM3 = 3; +constexpr uint8_t PARAM4 = 4; +constexpr uint8_t PARAM5 = 5; +constexpr uint8_t PARAM6 = 6; +constexpr uint8_t PARAM7 = 7; +constexpr uint8_t PARAM8 = 8; +constexpr uint8_t PARAM9 = 9; +constexpr uint8_t PARAM10 = 10; +constexpr uint8_t PARAM11 = 11; +constexpr uint8_t PARAM12 = 12; +constexpr uint8_t PARAM100 = 100; + +void getErrMsgCJSon(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info, + const char *info, const char *tag) { + status = napi_get_last_error_info(env, &extended_error_info); + if (status == napi_ok && extended_error_info != NULL) { + const char *errorMessage = + extended_error_info->error_message != NULL ? extended_error_info->error_message : "Unknown error"; + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "errmsg %{public}s!, engine_err_code %{public}d!.", + std::to_string(extended_error_info->engine_error_code).c_str(), extended_error_info->error_code); + std::string myInfo = info; + std::string res = "Failed to " + myInfo + " em = " + errorMessage + + ", eec = " + std::to_string(extended_error_info->engine_error_code) + + ", ec = " + std::to_string(extended_error_info->error_code); + napi_throw_error(env, NULL, res.c_str()); + } +} + +// [NAPI_GEN]: introduce function +napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) { + // [NAPI_GEN]: get function param in + size_t argc = 1; + napi_value args[1] = {nullptr}; + napi_status status; + const napi_extended_error_info *extended_error_info; + const char *tag = "[KH418_CJSON_Parse]"; + status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_get_cb_info", tag); + return nullptr; + } + napi_valuetype valuetype0; + status = napi_typeof(env, args[0], &valuetype0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_typeof", tag); + return nullptr; + } + size_t str_size0 = 0; + status = napi_get_value_string_utf8(env, args[0], NULL, 0, &str_size0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "get value string", tag); + return NULL; + } + char *valueIn0 = new char[str_size0 + 1]; + status = napi_get_value_string_utf8(env, args[0], valueIn0, str_size0 + 1, &str_size0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "get value string", tag); + delete[] valueIn0; + return NULL; + } + // delete[] valueIn0; // remember to delete memory + + // Todo: add business logic. + cJSON *json = cJSON_Parse(valueIn0); + int32_t myInt32Type = static_cast(json->type); + int32_t myInt32Valueint = static_cast(json->valueint); + char *valuestring = json->valuestring; + char *string2 = json->string; + const char * tset = "test"; + if (json->valuestring == NULL) { + valuestring = "json->valuestring is NULL"; + } + if (json->string == NULL) { + string2 = "json->string is NULL"; + } + cJSON *jsonNext = json->next; + napi_value nextOut; + status = napi_create_object(env, &nextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + napi_value typeNextOut; + if (jsonNext != NULL) { + int32_t myInt32NextType = static_cast(jsonNext->type); + status = napi_create_int32(env, myInt32NextType, &typeNextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, nextOut, "type", typeNextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + } + + napi_value childOut; + status = napi_create_object(env, &childOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + cJSON *jsonChild = json->child; + if (jsonChild != NULL) { + napi_value typeChildOut; + napi_value valuestringChildOut; + napi_value stringChildOut; + napi_value valueintChildOut; + napi_value valuedoubleChildOut; + + int32_t myInt32ChildType = static_cast(jsonChild->type); + status = napi_create_int32(env, myInt32ChildType, &typeChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, childOut, "type", typeChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + char *stringChild = jsonChild->string; + if (jsonChild->string == NULL) { + stringChild = "jsonChild->string is NULL"; + } + status = napi_create_string_utf8(env, stringChild, NAPI_AUTO_LENGTH, &stringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, childOut, "string", stringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + char *valuestringChild = jsonChild->valuestring; + if (jsonChild->valuestring == NULL) { + valuestringChild = "jsonChild->valuestring is NULL"; + } + status = napi_create_string_utf8(env, valuestringChild, NAPI_AUTO_LENGTH, &valuestringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, childOut, "valuestring", valuestringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + int32_t myInt32ChildValueint = static_cast(jsonChild->valueint); + status = napi_create_int32(env, myInt32ChildValueint, &valueintChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, childOut, "valueint", valueintChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + status = napi_create_double(env, json->valuedouble, &valuedoubleChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", tag); + return nullptr; + } + status = napi_set_named_property(env, childOut, "valuedouble", valuedoubleChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + } + + napi_value prevOut; + status = napi_create_object(env, &prevOut); + napi_value typePreOut; + cJSON *jsonPrev = json->prev; + if (jsonPrev != NULL) { + int32_t myInt32PreType = static_cast(jsonPrev->type); + status = napi_create_int32(env, myInt32PreType, &typePreOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, prevOut, "type", typePreOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + } + + + // [NAPI_GEN]: function return value + napi_value cJSON_ParseOut; + status = napi_create_object(env, &cJSON_ParseOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "next", nextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "prev", prevOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "child", childOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value typeOut; + status = napi_create_int32(env, myInt32Type, &typeOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "type", typeOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valuestringOut; + status = napi_create_string_utf8(env, valuestring, NAPI_AUTO_LENGTH, &valuestringOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valuestring", valuestringOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valueintOut; + status = napi_create_int32(env, myInt32Valueint, &valueintOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valueint", valueintOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valuedoubleOut; + status = napi_create_double(env, json->valuedouble, &valuedoubleOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valuedouble", valuedoubleOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value stringOut; + status = napi_create_string_utf8(env, string2, NAPI_AUTO_LENGTH, &stringOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "string", stringOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + return cJSON_ParseOut; +} diff --git a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts index 04fccb4e..7aa68819 100644 --- a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts +++ b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts @@ -45,6 +45,18 @@ export const testNapiGetElement: (a: object, b: number) => string; export const testNapiHasElement: (a: object, b: number) => string; export const testNapiDeleteElement: (a: object, b: number) => string; +export interface cJSON { + next: cJSON; + prev: cJSON; + child: cJSON; + type: number; + valuestring: string; + valueint: number; + valuedouble: number; + string: string; +} +export const KH418_cJSON_Parse:(value: string) => cJSON; + /* work_with_javascript_values_and_abstract_operations */ export const testNapiCoerceToBool: (a: any) => boolean; export const testNapiCoerceToNumber: (a: any) => number; diff --git a/examples/napitutorials/entry/src/ohosTest/ets/test/Ability.test.ets b/examples/napitutorials/entry/src/ohosTest/ets/test/Ability.test.ets index 2a012b4e..d18cee69 100644 --- a/examples/napitutorials/entry/src/ohosTest/ets/test/Ability.test.ets +++ b/examples/napitutorials/entry/src/ohosTest/ets/test/Ability.test.ets @@ -13,6 +13,7 @@ * limitations under the License. */ +import testNapi from 'libentry.so'; import hilog from '@ohos.hilog'; import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'; @@ -46,5 +47,23 @@ export default function abilityTest() { expect(a).assertContain(b); expect(a).assertEqual(a); }) + + it('KH418_cJSON_Parse', 0, () => { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let value = '{"name":"JohnDoe"}' + let result: testNapi.cJSON = testNapi.KH418_cJSON_Parse(value); + let value2 = '{"age":18}' + let result2: testNapi.cJSON = testNapi.KH418_cJSON_Parse(value2); + let value3 = '{"is_student":true}' + let result3: testNapi.cJSON = testNapi.KH418_cJSON_Parse(value3); + let value4 = '{"arrayTest":["a", "b"]}' + let result4: testNapi.cJSON = testNapi.KH418_cJSON_Parse(value4); + console.info("Test NAPI KH418_cJSON_Parse result1: ", JSON.stringify(result)) + console.info("Test NAPI KH418_cJSON_Parse result1: ", JSON.stringify(result2)) + console.info("Test NAPI KH418_cJSON_Parse result1: ", JSON.stringify(result3)) + console.info("Test NAPI KH418_cJSON_Parse result1: ", JSON.stringify(result4)) + // hilog.info(0x0000, "testTag", "Test NAPI KH418_cJSON_Parse result2: ", JSON.stringify(result)); + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. }) } \ No newline at end of file diff --git a/examples/napitutorials/tool/commandLine/src/function.json b/examples/napitutorials/tool/commandLine/src/function.json index 7aabaf2f..58a87b5f 100644 --- a/examples/napitutorials/tool/commandLine/src/function.json +++ b/examples/napitutorials/tool/commandLine/src/function.json @@ -1,13 +1,13 @@ { "directFunction": { "indexTemplete": "export const %s:(%s) => %s;\n", - "cppFuncTemplete": "#include \"napi/native_api.h\"\n[include_replace]\n\n[body_replace]\n\nEXTERN_C_START\nstatic napi_value Init(napi_env env, napi_value exports)\n{\n napi_property_descriptor desc[] = {\n [init_replace]\n};\nnapi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);\nreturn exports;\n}\nEXTERN_C_END\n\nstatic napi_module demoModule = {\n .nm_version = 1,\n .nm_flags = 0,\n .nm_filename = nullptr,\n .nm_register_func = Init,\n .nm_modname = \"entry\",\n .nm_priv = ((void*)0),\n .reserved = { 0 },\n};\n\nextern \"C\" __attribute__((constructor)) void RegisterEntryModule(void)\n{\n napi_module_register(&demoModule);\n}", + "cppFuncTemplete": "#include \"napi/native_api.h\"\n#include \n#include \n[include_replace]\n#define GLOBAL_RESMGR (0xFFEE)\nconstexpr int32_t STR_MAX_SIZE = 200;\nconstexpr int32_t LONG_STR_MAX_SIZE = 1024;\nconstexpr int32_t ERR_OK = 0;\nconstexpr int8_t NO_ERROR = 0;\nconstexpr int8_t ERROR = -1;\nconstexpr uint8_t PARAM0 = 0;\nconstexpr uint8_t PARAM1 = 1;\nconstexpr uint8_t PARAM2 = 2;\nconstexpr uint8_t PARAM3 = 3;\nconstexpr uint8_t PARAM4 = 4;\nconstexpr uint8_t PARAM5 = 5;\nconstexpr uint8_t PARAM6 = 6;\nconstexpr uint8_t PARAM7 = 7;\nconstexpr uint8_t PARAM8 = 8;\nconstexpr uint8_t PARAM9 = 9;\nconstexpr uint8_t PARAM10 = 10;\nconstexpr uint8_t PARAM11 = 11;\nconstexpr uint8_t PARAM12 = 12;\nconstexpr uint8_t PARAM100 = 100;\n\nvoid getErrMessage(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info,\n const char *info, const char *tag) {\n status = napi_get_last_error_info(env, &extended_error_info);\n if (status == napi_ok && extended_error_info != NULL) {\n const char *errorMessage =\n extended_error_info->error_message != NULL ? extended_error_info->error_message : \"Unknown error\";\n OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, \"errmsg %{public}s!, engine_err_code %{public}d!.\",\n std::to_string(extended_error_info->engine_error_code).c_str(), extended_error_info->error_code);\n std::string myInfo = info;\n std::string res = \"Failed to \" + myInfo + \" em = \" + errorMessage +\n \", eec = \" + std::to_string(extended_error_info->engine_error_code) +\n \", ec = \" + std::to_string(extended_error_info->error_code);\n napi_throw_error(env, NULL, res.c_str());\n }\n}\n\n[body_replace]\n\nEXTERN_C_START\nstatic napi_value Init(napi_env env, napi_value exports)\n{\n napi_property_descriptor desc[] = {\n [init_replace]\n};\nnapi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);\nreturn exports;\n}\nEXTERN_C_END\n\nstatic napi_module demoModule = {\n .nm_version = 1,\n .nm_flags = 0,\n .nm_filename = nullptr,\n .nm_register_func = Init,\n .nm_modname = \"entry\",\n .nm_priv = ((void*)0),\n .reserved = { 0 },\n};\n\nextern \"C\" __attribute__((constructor)) void RegisterEntryModule(void)\n{\n napi_module_register(&demoModule);\n}", "cppFuncDetails": { "funcInitTemplete": "{ \"%s\" , nullptr, %s, nullptr, nullptr, nullptr, napi_default, nullptr },", - "funcBodyTemplete": "static napi_value [funcName](napi_env env, napi_callback_info info)\n{\n[func_getParam_replace]\n [func_return_replace]\n }\n", - "funcGetParamTemplete" : "size_t requireArgc = [param_length];\n size_t argc = [param_length];\n napi_value args[[param_length]] = {nullptr};\n napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);\n [getParam_replace]\n ", - "funcReturnTemplete" : "[return_type_define]\n // Todo\n // eg. res = value0 + value1;\n napi_value result;\n [return_replace]\n return result;\n", - "paramGenTemplete": " napi_valuetype valuetype%s;\n napi_typeof(env, args[%s], &valuetype%s);\n %s value%s;\n [getParam_replace]", + "funcBodyTemplete": "// [NAPI_GEN]: introduce function\nnapi_value [funcName](napi_env env, napi_callback_info info)\n{\n // [NAPI_GEN]: get function param in\n[func_getParam_replace]\n [func_return_replace]\n}\n", + "funcGetParamTemplete" : " size_t argc = [param_length];\n napi_value args[[param_length]] = {nullptr};\n napi_status status;\n const napi_extended_error_info *extended_error_info;\n const char * tag = \"[[get_error_msg_tag]]\";\n status = napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);\n if(status != napi_ok) {\n getErrMessage(status, env,extended_error_info, \"napi_get_cb_info\",tag);\n return nullptr;\n }\n [getParam_replace]\n ", + "funcReturnTemplete" : "// Todo: add business logic.\n\n // [NAPI_GEN]: function return value\n [return_replace]\n return [return_name]Out;\n", + "paramGenTemplete": "napi_valuetype valuetype%s;\n status = napi_typeof(env, args[%s], &valuetype%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_typeof\", tag);\n return nullptr;\n }\n [getParam_replace]", "funcParamType": { "int32_t": "napi_get_value_int32(env, args[%s], &value%s);\n", "int64_t": "napi_get_value_int64(env, args[%s], &value%s);\n", @@ -15,20 +15,23 @@ "int": "", "double": "napi_get_value_double(env, args[%s], &value%s);\n", "bool": "napi_get_value_bool(env, args[%s], &value%s);\n", - "string": "char buf[1024];\n size_t results;\n napi_get_value_string_utf8(env, args[%s], buf, 1024, &results);\n value%s = buf;\n" + "string": "size_t str_size%s = 0;\n status = napi_get_value_string_utf8(env, args[%s], NULL, 0, &str_size%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n return NULL;\n }\n char *%sIn%s = new char[str_size%s + 1];\n status = napi_get_value_string_utf8(env, args[0], %sIn%s, str_size%s + 1, &str_size%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n delete[] %sIn%s;\n return NULL;\n }\n // delete[] %sIn%s; // remember to delete memory \n" }, "funcReturnType": { - "int32_t": "napi_create_int32(env, res, &result);\n", - "int64_t": "napi_create_int64(env, res, &result);\n", - "uint32_t": "napi_create_uint32(env, res, &result);\n", + "int32_t": " napi_value %sOut;\n status = napi_create_int32(env, 1, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_int32\", tag);\n return nullptr;\n }\n", + "int64_t": " napi_value %sOut;\n status = napi_create_int64(env, 1, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_int64\", tag);\n return nullptr;\n }\n", + "uint32_t": " napi_value %sOut;\n status = napi_create_uint32(env, 1, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_uint32\", tag);\n return nullptr;\n }\n", "int": "", "size_t": "", - "double": "napi_create_double(env, res, &result);\n", - "bool": "napi_get_boolean(env, res, &result);\n", - "string": "napi_create_string_utf8(env, res, NAPI_AUTO_LENGTH, &result);\n" - } + "double": " napi_value %sOut;\n status = napi_create_double(env, 1.0, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_double\", tag);\n return nullptr;\n }\n", + "bool": " napi_value %sOut;\n status = napi_get_boolean(env, true, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_get_boolean\", tag);\n return nullptr;\n }\n", + "string": " napi_value %sOut;\n status = napi_create_string_utf8(env, \"%s\", NAPI_AUTO_LENGTH, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_string_utf8\", tag);\n return nullptr;\n }\n", + "object": " napi_value %sOut;\n status = napi_create_object(env, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_object\", tag);\n return nullptr;\n }\n" + }, + "funcReturnObjectToSet": " status = napi_set_named_property(env, %sOut, \"%s\", %sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_set_named_property\", tag);\n return nullptr;\n }\n", + "funcParamObjectToGet": "" }, - "abilityTestTemplete": "it('assertContain_[random_number]', 0, () => {\n // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.\n hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');\n\n [func_direct_testCase]\n\n // Defines a variety of assertion methods, which are used to declare expected boolean conditions.\n // 断言 如:expect(result).assertEqual(2+3)\n })\n" + "abilityTestTemplete": " it('[test_case_name]', 0, () => {\n // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.\n hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');\n\n [func_direct_testCase]\n\n // Defines a variety of assertion methods, which are used to declare expected boolean conditions.\n // 断言 如:expect(result).assertEqual(2+3)\n })\n" }, "asyncFunction": { } diff --git a/examples/napitutorials/tool/commandLine/src/napiGen/functionDirect.js b/examples/napitutorials/tool/commandLine/src/napiGen/functionDirect.js index 810b00c1..a64f41b7 100644 --- a/examples/napitutorials/tool/commandLine/src/napiGen/functionDirect.js +++ b/examples/napitutorials/tool/commandLine/src/napiGen/functionDirect.js @@ -22,6 +22,18 @@ const re = require("../tools/re"); const LENGTH = 10; const TWO_DECIMAL = 2; +function analyzeRetIsObject(retType, objectInfo) { + // 去除 * 和 空格 + retType = retType.replace('*', '').replace('struct', '').trim() + let objKeys = Object.keys(objectInfo) + for (let i = 0; i < objKeys.length; i++) { + if (retType == objKeys[i]) { + return true; + } + } + return false; +} + function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) { let funcInfo = { "name": "", @@ -31,14 +43,14 @@ function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) // 获取.h文件中的头文件 let includes = params.includes let includes_replace = '' - for(let i in includes) { + for (let i in includes) { includes_replace += util.format('#include %s\n', includes[i]) } // 获取注册的方法名字 (只读取了一个方法 当前只支持一个方法的转换) funcInfo.name = params.functions[0].name - let serialNum = tsFuncName.substring(0,6) - let funcName_replace = serialNum + funcInfo.name.substring(0,1).toUpperCase() + funcInfo.name.substring(1,funcInfo.name.length) + let serialNum = tsFuncName.substring(0, 6) + let funcName_replace = serialNum + funcInfo.name.substring(0, 1).toUpperCase() + funcInfo.name.substring(1, funcInfo.name.length) // 方法的注册 let initTemplete = directFuncJson.cppFuncDetails.funcInitTemplete @@ -46,8 +58,8 @@ function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) // 分析方法 funcInfo.retType = params.functions[0].rtnType - let parseParams = params.functions[0].parameters - for(let i = 0; i < parseParams.length; ++i) { + let parseParams = params.functions[0].parameters + for (let i = 0; i < parseParams.length; ++i) { let param = createParam(parseParams[i]) funcInfo.params.push(param) } @@ -57,10 +69,11 @@ function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) let funcParamType = directFuncJson.cppFuncDetails.funcParamType let paramGenResult = '' // napi 获取参数 - for(let i = 0; i < funcInfo.params.length; i++) { - console.info("funcInfo.params[i].type.substring(0,10): " + funcInfo.params[i].type.substring(0,10)) - let paramType = funcInfo.params[i].type === 'size_t'? 'int64_t': funcInfo.params[i].type - let paramGen = util.format(paramGenTemplete, i, i, i, paramType, i) + for (let i = 0; i < funcInfo.params.length; i++) { + console.info("funcInfo.params[i].type.substring(0,10): " + funcInfo.params[i].type.substring(0, 10)) + let paramType = funcInfo.params[i].type === 'size_t' ? 'int64_t' : funcInfo.params[i].type + let paramName = funcInfo.params[i].name + let paramGen = util.format(paramGenTemplete, i, i, i) if (funcInfo.params[i].type === 'double') { let getParam = util.format(funcParamType.double, i, i) paramGen = replaceAll(paramGen, '[getParam_replace]', getParam); @@ -81,50 +94,43 @@ function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) let getParam = util.format(funcParamType.bool, i, i) paramGen = replaceAll(paramGen, '[getParam_replace]', getParam); paramGenResult += paramGen; - } else if (funcInfo.params[i].type === 'std::string' || funcInfo.params[i].type.substring(0,10) === 'const char') { - let getParam = util.format(funcParamType.string, i, i) + } else if (funcInfo.params[i].type === 'std::string' || funcInfo.params[i].type.substring(0, 10) === 'const char') { + let getParam = util.format(funcParamType.string, i, i, i, paramName, i, i, paramName, i, i, i, paramName, i, paramName, i) paramGen = replaceAll(paramGen, '[getParam_replace]', getParam); paramGenResult += paramGen; } } - // 返回值处理 + + // 返回值处理 对于对象要使用循环处理 let retGenResult = '' - let funcReturnType = directFuncJson.cppFuncDetails.funcReturnType - if (funcInfo.retType === 'uint32_t') { - retGenResult = funcReturnType.uint32_t - } else if (funcInfo.retType === 'double') { - retGenResult = funcReturnType.double - } else if (funcInfo.retType === 'int32_t') { - retGenResult = funcReturnType.int32_t - } else if (funcInfo.retType === 'int64_t' || funcInfo.retType === 'size_t') { - retGenResult = funcReturnType.int64_t - } else if (funcInfo.retType === 'bool') { - retGenResult = funcReturnType.bool - } else if (funcInfo.retType === 'std::string' || funcInfo.retType.substring(0,10) === 'const char') { - retGenResult = funcReturnType.string + let retObjInfo = { + "objName": '', + "flag": false } + retGenResult = returnTypeC2Js(directFuncJson, funcInfo, params, retGenResult, retObjInfo); let bodyTemplete = directFuncJson.cppFuncDetails.funcBodyTemplete let body_replace = replaceAll(bodyTemplete, '[funcName]', funcName_replace) let funcGetParamTemplete = directFuncJson.cppFuncDetails.funcGetParamTemplete let genParam_replace = replaceAll(funcGetParamTemplete, '[param_length]', funcInfo.params.length) genParam_replace = replaceAll(genParam_replace, '[getParam_replace]', paramGenResult) + genParam_replace = replaceAll(genParam_replace, '[get_error_msg_tag]', funcName_replace) if (funcInfo.params.length !== 0) { body_replace = replaceAll(body_replace, '[func_getParam_replace]', genParam_replace) } else { body_replace = replaceAll(body_replace, '[func_getParam_replace]', '') } - if(funcInfo.retType !== 'void') { - let returnType = funcInfo.retType === 'std::string'? 'const char *': funcInfo.retType - returnType = returnType === 'size_t'? 'int64_t': returnType + if (funcInfo.retType !== 'void') { + let returnType = funcInfo.retType === 'std::string' ? 'const char *' : funcInfo.retType + returnType = returnType === 'size_t' ? 'int64_t' : returnType let funcReturnTemplete = directFuncJson.cppFuncDetails.funcReturnTemplete - let func_return_replace = replaceAll(funcReturnTemplete, '[return_type_define]', returnType + ' res;') - func_return_replace = replaceAll(func_return_replace, '[return_replace]', retGenResult) - body_replace = replaceAll(body_replace, '[func_return_replace]', func_return_replace) + let = func_return_replace = replaceAll(funcReturnTemplete, '[return_name]', retObjInfo.objName) + func_return_replace = replaceAll(func_return_replace, '[return_replace]', retGenResult) + body_replace = replaceAll(body_replace, '[func_return_replace]', func_return_replace) } else { - body_replace = replaceAll(body_replace, '[func_return_replace]', '') + body_replace = replaceAll(body_replace, '[func_return_replace]', '') } - body_replace = replaceAll(body_replace, '[return_replace]', retGenResult) + body_replace = replaceAll(body_replace, '[return_replace]', retGenResult) // 将内容写入cpp文件 // 先判断cppFilePath是否存在,若存在则追加写入内容 @@ -162,6 +168,80 @@ function generateDirectFunction(params, tsFuncName, cppFilePath, directFuncJson) } } +function returnTypeC2Js(directFuncJson, funcInfo, params, retGenResult, retObjInfo) { + let funcReturnType = directFuncJson.cppFuncDetails.funcReturnType; + let setRetProperty = directFuncJson.cppFuncDetails.funcReturnObjectToSet + let returnName = funcInfo.name; + if (!retObjInfo.flag) { + retObjInfo.objName = returnName + } + if (funcInfo.retType === 'uint32_t') { + retGenResult += util.format(funcReturnType.uint32_t, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (funcInfo.retType === 'double') { + retGenResult += util.format(funcReturnType.double, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (funcInfo.retType === 'int32_t' || funcInfo.retType === 'int') { + retGenResult += util.format(funcReturnType.int32_t, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (funcInfo.retType === 'int64_t' || funcInfo.retType === 'size_t') { + retGenResult += util.format(funcReturnType.int64_t, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (funcInfo.retType === 'bool') { + retGenResult += util.format(funcReturnType.bool, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (funcInfo.retType === 'std::string' || funcInfo.retType.substring(0, 10) === 'const char' + || funcInfo.retType === 'char *') { + retGenResult += util.format(funcReturnType.string, returnName, returnName, returnName); + if (retObjInfo.flag) { + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } else if (analyzeRetIsObject(funcInfo.retType, params.classes)) { // 返回值是对象 + if (!retObjInfo.flag) { + retGenResult += util.format(funcReturnType.object, returnName, returnName); + retObjInfo.flag = true + let retType = funcInfo.retType.replace('*', '').trim(); + let objectName = ''; + let objectProperty = []; + + let myObject = params.classes[retType] + objectName = myObject.bare_name; + let myObjectProperty = myObject.properties.public; + for (let j = 0; j < myObjectProperty.length; j++) { + let propertyObj = { + "name": '', + "retType": '' + } + propertyObj.name = myObjectProperty[j].name; + propertyObj.retType = myObjectProperty[j].type; + + objectProperty.push(propertyObj); + } + // 遍历属性 + for (let i = 0; i < objectProperty.length; i++) { + let testRes = returnTypeC2Js(directFuncJson, objectProperty[i], params, retGenResult, retObjInfo) + retGenResult = testRes; + } + } else { + if (retObjInfo.objName !== '') { + retGenResult += util.format(funcReturnType.object, returnName, returnName); + retGenResult += util.format(setRetProperty, retObjInfo.objName, returnName, returnName) + } + } + } + return retGenResult; +} + function replaceAll(s, sfrom, sto) { while (s.indexOf(sfrom) >= 0) { s = s.replace(sfrom, sto) diff --git a/examples/napitutorials/tool/commandLine/src/napiGen/functionDirectTest.js b/examples/napitutorials/tool/commandLine/src/napiGen/functionDirectTest.js index eb854329..03aac05f 100644 --- a/examples/napitutorials/tool/commandLine/src/napiGen/functionDirectTest.js +++ b/examples/napitutorials/tool/commandLine/src/napiGen/functionDirectTest.js @@ -19,7 +19,6 @@ const path = require('path') const fs = require("fs"); const LENGTH = 10; const TWO_DECIMAL = 2; -const SERIAL = 5; const MODTWO = 2; // 随机生成浮点数值 @@ -85,17 +84,15 @@ function generateFuncTestCase(params, tsFuncName, testFilePath, directFuncJson) let index = funcParamUse.lastIndexOf(', '); funcParamUse = funcParamUse.substring(0, index); // 调用函数 - let callFunc = util.format('let result: %s = testNapi.%s(%s)\n', getJsType(funcInfo.retType), tsFuncName, funcParamUse) + let callFunc = util.format(' let result: %s = testNapi.%s(%s)\n', getJsType(funcInfo.retType), tsFuncName, funcParamUse) // 加 hilog 打印 - let hilogContent = util.format('hilog.info(0x0000, "testTag", "Test NAPI %s: ", result);', tsFuncName) + let hilogContent = util.format(' hilog.info(0x0000, "testTag", "Test NAPI %s: ", result);', tsFuncName) let func_test_replace = funcParamDefine + callFunc + hilogContent let abilityTestTemplete = directFuncJson.abilityTestTemplete - // 替换random_number - let serialNum = tsFuncName.substring(0,SERIAL) - console.info("serialNum: " + serialNum) + // 替换test_case_name let funcTestContent = replaceAll(abilityTestTemplete,'[func_direct_testCase]', func_test_replace) - funcTestContent = replaceAll(funcTestContent, '[random_number]', serialNum) - //console.info("funcTestContent: " + funcTestContent) + funcTestContent = replaceAll(funcTestContent, '[test_case_name]', tsFuncName) + //console.info("funcTestContent: " + funcTestContent) // 将内容写入Ability.test.ets文件 // 1.追加写入import模块 写在第一个import之前 // 2.追加写入测试用例 @@ -152,6 +149,9 @@ function getJsType(type) { return 'string' } else if (type === 'bool') { return 'boolean' + } else { + // 对象,在ts中定义为interface + return 'testNapi.' + type.replace('*', '').trim() } } diff --git a/examples/napitutorials/tool/commandLine/src/tsGen/tsMain.js b/examples/napitutorials/tool/commandLine/src/tsGen/tsMain.js index ee85c383..a6110013 100644 --- a/examples/napitutorials/tool/commandLine/src/tsGen/tsMain.js +++ b/examples/napitutorials/tool/commandLine/src/tsGen/tsMain.js @@ -26,11 +26,12 @@ const { generateFuncTestCase } = require('../napiGen/functionDirectTest') const MIN_RANDOM = 100 const MAX_RANDOM = 999 let tsFuncName = '' + function parseFileAll(hFilePath) { let execSync = require("child_process").execSync let cmd = "" // node命令直接执行 - if(fs.existsSync("tool/commandLine/src/tsGen/header_parser.py")) { + if (fs.existsSync("tool/commandLine/src/tsGen/header_parser.py")) { cmd = "python tool/commandLine/src/tsGen/header_parser.py " + hFilePath } else { // call exe file (for real runtime) @@ -48,14 +49,33 @@ function parseFileAll(hFilePath) { return parseResult } +function createNameSpaceInfo(parseNameSpaceInfo) { + let nameSpaceInfo = { + "name": "", + "classes": [], + "functions": [] + } + nameSpaceInfo.name = parseNameSpaceInfo + return nameSpaceInfo +} + +function analyzeNameSpace(rootInfo, parseResult) { + let parseNameSpaces = parseResult.namespaces + for (var i = 0; i < parseNameSpaces.length; ++i) { + let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i]) + rootInfo.namespaces.push(nameSpaceInfo) + } +} + function isStringType(cType) { - switch(cType) { + switch (cType) { case 'string': case 'std::string': case 'char': case 'wchar_t': case 'char16_t': case 'char32_t': + case 'char *': return true default: return false @@ -70,7 +90,7 @@ function isBoolType(cType) { } function isNumberType(cType) { - switch(cType) { + switch (cType) { case 'short': case 'int': case 'uint32_t': @@ -116,7 +136,7 @@ function getJsTypeFromC(cType, typeInfo) { } let unsignedIdx = basicCtype.indexOf('unsigned') - if ( unsignedIdx >= 0) { + if (unsignedIdx >= 0) { // cut off the keywords 'unsigned' basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim() } @@ -124,6 +144,13 @@ function getJsTypeFromC(cType, typeInfo) { if (typeInfo.array) { jsType = util.format("Array<%s>", jsType) } + // struct cJson * 的情况 + let matchStruct = re.match("struct[A-Z_a-z0-9 *]+", basicCtype); + if (matchStruct) { + let index = basicCtype.indexOf('struct') + // 去掉struct和* + jsType = jsType.substring(index + 6, basicCtype.length).replace('*', '').trim() + } return jsType } @@ -145,7 +172,7 @@ function createFuncInfo(parseFuncInfo, isClassFunc) { "params": [], "namespace": "", "retType": "", - "static":"" + "static": "" } funcInfo.name = parseFuncInfo.name funcInfo.namespace = parseFuncInfo.namespace @@ -157,7 +184,7 @@ function createFuncInfo(parseFuncInfo, isClassFunc) { let parseParams = parseFuncInfo.parameters // console.info("parseParams: " + JSON.stringify(parseParams)) - for(var i = 0; i < parseParams.length; ++i) { + for (var i = 0; i < parseParams.length; ++i) { let param = createParam(parseParams[i]) funcInfo.params.push(param) } @@ -172,19 +199,97 @@ function createFuncInfo(parseFuncInfo, isClassFunc) { return funcInfo } +function putFuncIntoNamespace(funcInfo, namespaces) { + for (var i = 0; i < namespaces.length; ++i) { + if (namespaces[i].name === funcInfo.namespace) { + namespaces[i].functions.push(funcInfo) + return + } + } + // NapiLog.logError('The namespace [%s] of function %s is not found.'.format(funcInfo.namespace, funcInfo.name)); +} + function analyzeRootFunction(rootInfo, parseResult) { let parseFunctions = parseResult.functions - // console.info("parseFunctions: " + JSON.stringify(parseFunctions)) - for(var i = 0; i < parseFunctions.length; ++i) { + // console.info("parseFunctions: " + JSON.stringify(parseFunctions)) + for (var i = 0; i < parseFunctions.length; ++i) { // 普通方法生成模板 let funcInfo = createFuncInfo(parseFunctions[i], false) - rootInfo.functions.push(funcInfo) + //rootInfo.functions.push(funcInfo) + if (parseFunctions[i].namespace != '') { + // function in namespace + putFuncIntoNamespace(funcInfo, rootInfo.namespaces) + } else { + // function without namespace, put on root + rootInfo.functions.push(funcInfo) + } + } +} + +function createProperties(parseProperties) { + let propertyList = [] + for (var i = 0; i < parseProperties.length; ++i) { + let property = {} + property.name = parseProperties[i].name + property.type = getJsTypeFromC(parseProperties[i].type, parseProperties[i]) + propertyList.push(property) + } + return propertyList +} + +function createClassFunctions(parseFuncs) { + let funcList = [] + for (var i = 0; i < parseFuncs.length; ++i) { + let funcInfo = createFuncInfo(parseFuncs[i], true) + funcList.push(funcInfo) + } + return funcList +} + +function createClassInfo(parseClassInfo) { + let classInfo = { + "name": "", + "namespace": "", + "properties": [], + "functions": [], + "extends": [] + } + classInfo.name = parseClassInfo.name + classInfo.namespace = parseClassInfo.namespace + classInfo.properties = createProperties(parseClassInfo.properties.public) + classInfo.functions = createClassFunctions(parseClassInfo.methods.public) + + return classInfo +} + +function putClassIntoNamespace(classInfo, namespaces) { + for (var i = 0; i < namespaces.length; ++i) { + if (namespaces[i].name === classInfo.namespace) { + namespaces[i].classes.push(classInfo) + return + } + } + // NapiLog.logError('The namespace [%s] of class %s is not found.'.format(classInfo.namespace, classInfo.name)); +} + +function analyzeClasses(rootInfo, parseResult) { + let parseClasses = parseResult.classes; + + for (var className in parseClasses) { + let classInfo = createClassInfo(parseClasses[className]) + if (classInfo.namespace != '') { + // class in namespace + putClassIntoNamespace(classInfo, rootInfo.namespaces) + } else { + // class without namespace, put on root + rootInfo.classes.push(classInfo) + } } } function getTab(tabLv) { let tab = "" - for(var i = 0; i < tabLv; ++i) { + for (var i = 0; i < tabLv; ++i) { tab += " " } return tab @@ -197,16 +302,47 @@ function genFunction(func, funcJson) { funcParams += i > 0 ? ", " : "" funcParams += func.params[i].name + ": " + func.params[i].type } - let indexTemplete = funcJson.directFunction.indexTemplete tsFuncName = 'KH' + generateRandomInteger(MIN_RANDOM, MAX_RANDOM) + '_' + func.name return util.format(indexTemplete, tsFuncName, funcParams, func.retType) } +function genClass(classInfo, tabLv, needDeclare = false) { + let tab = getTab(tabLv) + let tsClass = tab + 'export ' + "interface " + classInfo.name + " {\n" + let tab1 = getTab(tabLv + 1) + for (var i = 0; i < classInfo.properties.length; ++i) { + tsClass += util.format("%s%s: %s;\n", tab1, classInfo.properties[i].name, classInfo.properties[i].type) + } + tsClass += tab + "}\n" + return tsClass +} + +function genNamespace(namespace, tabLv) { + let tab = getTab(tabLv) + let tsNamespace = tab + util.format("declare namespace %s {\n", namespace.name) + for (var i = 0; i < namespace.functions.length; ++i) { + tsNamespace += genFunction(namespace.functions[i], tabLv + 1) + } + for (var i = 0; i < namespace.classes.length; ++i) { + tsNamespace += genClass(namespace.classes[i], tabLv + 1) + } + tsNamespace += tab + "}\n" + return tsNamespace +} + function genTsContent(rootInfo, funcJson) { let tsContent = rootInfo.needCallback ? "import { AsyncCallback, Callback } from './../basic';\n\n" : "" - for(var i = 0; i < rootInfo.functions.length; ++i) { + for (var i = 0; i < rootInfo.classes.length; ++i) { + tsContent += genClass(rootInfo.classes[i], 0, true) + } + + for (var i = 0; i < rootInfo.namespaces.length; ++i) { + tsContent += genNamespace(rootInfo.namespaces[i], 0) + } + + for (var i = 0; i < rootInfo.functions.length; ++i) { tsContent += genFunction(rootInfo.functions[i], funcJson) } @@ -226,13 +362,10 @@ function removeMarco(hFilePath, tempFilePath) { // 逐行读取文件内容并处理 rl.on('line', (line) => { let tt = re.match('[A-Z_]+\([A-Za-z_ *]+\)', line) - console.info("tt: " + JSON.stringify(tt)) if (tt) { - console.info("before line: " + line) let removeContent = re.getReg(line, tt.regs[0]) line = line.substring(removeContent.length + 1, line.length) let index = line.indexOf(') ') - console.info("index: " + index) if (index >= 0) { line = line.substring(0, index) + line.substring(index + 1, line.length) } @@ -242,7 +375,6 @@ function removeMarco(hFilePath, tempFilePath) { // 完成读取操作 rl.on('close', () => { - console.log("processedContent: " + processedContent); writeFile(tempFilePath, processedContent) }); } @@ -257,7 +389,7 @@ async function doGenerate(hFilePath, testFilePath, tsFilePath, cppFilePath) { let tempFilePath = path.join(hFilePath, tempFileName) removeMarco(hFilePath, tempFilePath) - while(!fs.existsSync(tempFilePath)) { + while (!fs.existsSync(tempFilePath)) { await sleep(20); // 延迟 20 毫秒 } const fileContent = fs.readFileSync(tempFilePath, 'utf8'); @@ -267,20 +399,20 @@ async function doGenerate(hFilePath, testFilePath, tsFilePath, cppFilePath) { console.info("parseResult.functions: " + JSON.stringify(parseResult.functions)) let rootInfo = { + "namespaces": [], + "classes": [], "functions": [], "needCallback": false } - // 普通方法生成一个模板模板 + + analyzeNameSpace(rootInfo, parseResult) analyzeRootFunction(rootInfo, parseResult) - // 如果是class生成一个模板 - // analyzeRootClass() + analyzeClasses(rootInfo, parseResult) // 读取Json文件 let funcJsonPath = path.join(__dirname, '../function.json'); - console.info("funcJsonPath: " + funcJsonPath) let funcJson = getJsonCfg(funcJsonPath); - let hfileName = path.basename(hFilePath, ".h") let tsContent = genTsContent(rootInfo, funcJson) console.info("tsContent: " + tsContent) appendWriteFile(tsFilePath, '\n' + tsContent) -- Gitee From b0ffa97cb489f6c05b932aeb4098365603b667b1 Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 11:37:30 +0800 Subject: [PATCH 2/6] fix: fix codeCheck Signed-off-by: gou-jingjing --- .../napitutorials/entry/src/main/cpp/init.cpp | 2 +- .../cpp/ncpp/cjsoncase/cjsonparsecase.cpp | 429 +++++++++++------- .../tool/commandLine/src/function.json | 4 +- 3 files changed, 263 insertions(+), 172 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/init.cpp b/examples/napitutorials/entry/src/main/cpp/init.cpp index fc7f313a..780c0b95 100644 --- a/examples/napitutorials/entry/src/main/cpp/init.cpp +++ b/examples/napitutorials/entry/src/main/cpp/init.cpp @@ -71,7 +71,7 @@ static napi_value Init(napi_env env, napi_value exports) {"cjson_version", nullptr, cJSONVersion, nullptr, nullptr, nullptr, napi_default, nullptr}, {"getContext", nullptr, NativeXComponentSample::PluginManager::GetContext, nullptr, nullptr, nullptr, napi_default, nullptr}, - {"KH418_cJSON_Parse", nullptr, KH418_CJSON_Parse, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"KH418_cJSON_Parse", nullptr, KH418_CJSON_Parse, nullptr, nullptr, nullptr, napi_default, nullptr}, }; napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp index 0a3b53b8..6680dd57 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp @@ -1,8 +1,22 @@ +/* + * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development 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. + */ #include "cjson/cJSON.h" #include "napi/native_api.h" +#include #include #include -#include #define GLOBAL_RESMGR (0xFFEE) constexpr int32_t STR_MAX_SIZE = 200; @@ -25,8 +39,11 @@ constexpr uint8_t PARAM11 = 11; constexpr uint8_t PARAM12 = 12; constexpr uint8_t PARAM100 = 100; +static const char *TAG = "[KH418_CJSON_Parse]"; + void getErrMsgCJSon(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info, - const char *info, const char *tag) { + const char *info, const char *tag) +{ status = napi_get_last_error_info(env, &extended_error_info); if (status == napi_ok && extended_error_info != NULL) { const char *errorMessage = @@ -41,263 +58,337 @@ void getErrMsgCJSon(napi_status &status, napi_env &env, const napi_extended_erro } } -// [NAPI_GEN]: introduce function -napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) { - // [NAPI_GEN]: get function param in - size_t argc = 1; - napi_value args[1] = {nullptr}; +napi_value cJsonParsePrevOut(napi_env env, cJSON *json) +{ napi_status status; const napi_extended_error_info *extended_error_info; - const char *tag = "[KH418_CJSON_Parse]"; - status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + napi_value prevOut; + status = napi_create_object(env, &prevOut); + napi_value typePreOut; + cJSON *jsonPrev = json->prev; + if (jsonPrev != NULL) { + int32_t myInt32PreType = static_cast(jsonPrev->type); + status = napi_create_int32(env, myInt32PreType, &typePreOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); + return nullptr; + } + status = napi_set_named_property(env, prevOut, "type", typePreOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); + return nullptr; + } + } + return prevOut; +} + +napi_value getChildTypeOut(napi_env env, napi_value childOut, cJSON *jsonChild) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_value typeChildOut; + int32_t myInt32ChildType = static_cast(jsonChild->type); + status = napi_create_int32(env, myInt32ChildType, &typeChildOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_get_cb_info", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); return nullptr; } - napi_valuetype valuetype0; - status = napi_typeof(env, args[0], &valuetype0); + status = napi_set_named_property(env, childOut, "type", typeChildOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_typeof", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } - size_t str_size0 = 0; - status = napi_get_value_string_utf8(env, args[0], NULL, 0, &str_size0); + return childOut; +} + +napi_value getChildStringOut(napi_env env, napi_value childOut, char *stringChild) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_value stringChildOut; + status = napi_create_string_utf8(env, stringChild, NAPI_AUTO_LENGTH, &stringChildOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "get value string", tag); - return NULL; + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", TAG); + return nullptr; } - char *valueIn0 = new char[str_size0 + 1]; - status = napi_get_value_string_utf8(env, args[0], valueIn0, str_size0 + 1, &str_size0); + status = napi_set_named_property(env, childOut, "string", stringChildOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "get value string", tag); - delete[] valueIn0; - return NULL; + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; } - // delete[] valueIn0; // remember to delete memory - - // Todo: add business logic. - cJSON *json = cJSON_Parse(valueIn0); - int32_t myInt32Type = static_cast(json->type); - int32_t myInt32Valueint = static_cast(json->valueint); - char *valuestring = json->valuestring; - char *string2 = json->string; - const char * tset = "test"; - if (json->valuestring == NULL) { - valuestring = "json->valuestring is NULL"; + return childOut; +} + +napi_value getChildValueStringOut(napi_env env, napi_value childOut, char *valuestringChild) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_value valuestringChildOut; + status = napi_create_string_utf8(env, valuestringChild, NAPI_AUTO_LENGTH, &valuestringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", TAG); + return nullptr; } - if (json->string == NULL) { - string2 = "json->string is NULL"; + status = napi_set_named_property(env, childOut, "valuestring", valuestringChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; } - cJSON *jsonNext = json->next; - napi_value nextOut; - status = napi_create_object(env, &nextOut); + return childOut; +} + +napi_value getChildValueIntOut(napi_env env, napi_value childOut, cJSON *jsonChild) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_value valueintChildOut; + int32_t myInt32ChildValueint = static_cast(jsonChild->valueint); + status = napi_create_int32(env, myInt32ChildValueint, &valueintChildOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); return nullptr; } - napi_value typeNextOut; - if (jsonNext != NULL) { - int32_t myInt32NextType = static_cast(jsonNext->type); - status = napi_create_int32(env, myInt32NextType, &typeNextOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); - return nullptr; - } - status = napi_set_named_property(env, nextOut, "type", typeNextOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } + status = napi_set_named_property(env, childOut, "valueint", valueintChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; + } + return childOut; +} + +napi_value getChildValueDoubleOut(napi_env env, napi_value childOut, cJSON *jsonChild) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_value valuedoubleChildOut; + status = napi_create_double(env, jsonChild->valuedouble, &valuedoubleChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", TAG); + return nullptr; } - + status = napi_set_named_property(env, childOut, "valuedouble", valuedoubleChildOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; + } + return childOut; +} + +napi_value cJsonParseChildOut(napi_env env, cJSON *json) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; napi_value childOut; status = napi_create_object(env, &childOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", TAG); return nullptr; } cJSON *jsonChild = json->child; if (jsonChild != NULL) { - napi_value typeChildOut; - napi_value valuestringChildOut; - napi_value stringChildOut; - napi_value valueintChildOut; - napi_value valuedoubleChildOut; - - int32_t myInt32ChildType = static_cast(jsonChild->type); - status = napi_create_int32(env, myInt32ChildType, &typeChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); - return nullptr; - } - status = napi_set_named_property(env, childOut, "type", typeChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } + childOut = getChildTypeOut(env, childOut, jsonChild); char *stringChild = jsonChild->string; if (jsonChild->string == NULL) { stringChild = "jsonChild->string is NULL"; } - status = napi_create_string_utf8(env, stringChild, NAPI_AUTO_LENGTH, &stringChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); - return nullptr; - } - status = napi_set_named_property(env, childOut, "string", stringChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } - + childOut = getChildStringOut(env, childOut, stringChild); char *valuestringChild = jsonChild->valuestring; if (jsonChild->valuestring == NULL) { valuestringChild = "jsonChild->valuestring is NULL"; } - status = napi_create_string_utf8(env, valuestringChild, NAPI_AUTO_LENGTH, &valuestringChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); - return nullptr; - } - status = napi_set_named_property(env, childOut, "valuestring", valuestringChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } - - int32_t myInt32ChildValueint = static_cast(jsonChild->valueint); - status = napi_create_int32(env, myInt32ChildValueint, &valueintChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); - return nullptr; - } - status = napi_set_named_property(env, childOut, "valueint", valueintChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } + childOut = getChildValueStringOut(env, childOut, valuestringChild); + childOut = getChildValueIntOut(env, childOut, jsonChild); + childOut = getChildValueDoubleOut(env, childOut, jsonChild); + } + return childOut; +} - status = napi_create_double(env, json->valuedouble, &valuedoubleChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", tag); - return nullptr; - } - status = napi_set_named_property(env, childOut, "valuedouble", valuedoubleChildOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } +napi_value cJsonParseNextOut(napi_env env, cJSON *json) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + cJSON *jsonNext = json->next; + napi_value nextOut; + status = napi_create_object(env, &nextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", TAG); + return nullptr; } - - napi_value prevOut; - status = napi_create_object(env, &prevOut); - napi_value typePreOut; - cJSON *jsonPrev = json->prev; - if (jsonPrev != NULL) { - int32_t myInt32PreType = static_cast(jsonPrev->type); - status = napi_create_int32(env, myInt32PreType, &typePreOut); + napi_value typeNextOut; + if (jsonNext != NULL) { + int32_t myInt32NextType = static_cast(jsonNext->type); + status = napi_create_int32(env, myInt32NextType, &typeNextOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); return nullptr; } - status = napi_set_named_property(env, prevOut, "type", typePreOut); + status = napi_set_named_property(env, nextOut, "type", typeNextOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } } + return nextOut; +} +char *getInfo(napi_env env, napi_value param0) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + napi_valuetype valuetype0; + status = napi_typeof(env, param0, &valuetype0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_typeof", TAG); + return nullptr; + } + size_t strSize0 = 0; + status = napi_get_value_string_utf8(env, param0, NULL, 0, &strSize0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "get value string", TAG); + return NULL; + } + char *valueIn0 = new char[strSize0 + 1]; + status = napi_get_value_string_utf8(env, param0, valueIn0, strSize0 + 1, &strSize0); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "get value string", TAG); + delete[] valueIn0; + return NULL; + } + return valueIn0; +} - // [NAPI_GEN]: function return value - napi_value cJSON_ParseOut; - status = napi_create_object(env, &cJSON_ParseOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); +napi_value getReturnObj(napi_env env, napi_value cJSON_ParseOut, napi_value nextOut, napi_value prevOut, + napi_value childOut, int32_t myInt32Type) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; + status = napi_set_named_property(env, cJSON_ParseOut, "next", nextOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "prev", prevOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "child", childOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); - return nullptr; - } - status = napi_set_named_property(env, cJSON_ParseOut, "next", nextOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); - return nullptr; - } - status = napi_set_named_property(env, cJSON_ParseOut, "prev", prevOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } - - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", tag); - return nullptr; - } - status = napi_set_named_property(env, cJSON_ParseOut, "child", childOut); - if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); - return nullptr; - } napi_value typeOut; status = napi_create_int32(env, myInt32Type, &typeOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); return nullptr; } status = napi_set_named_property(env, cJSON_ParseOut, "type", typeOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + return cJSON_ParseOut; +} + +napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestring, int32_t myInt32Valueint, + double myValueDouble, char *string2) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; napi_value valuestringOut; status = napi_create_string_utf8(env, valuestring, NAPI_AUTO_LENGTH, &valuestringOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", TAG); return nullptr; } status = napi_set_named_property(env, cJSON_ParseOut, "valuestring", valuestringOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + napi_value valueintOut; status = napi_create_int32(env, myInt32Valueint, &valueintOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_int32", TAG); return nullptr; } status = napi_set_named_property(env, cJSON_ParseOut, "valueint", valueintOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + napi_value valuedoubleOut; - status = napi_create_double(env, json->valuedouble, &valuedoubleOut); + status = napi_create_double(env, myValueDouble, &valuedoubleOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_double", TAG); return nullptr; } status = napi_set_named_property(env, cJSON_ParseOut, "valuedouble", valuedoubleOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + napi_value stringOut; status = napi_create_string_utf8(env, string2, NAPI_AUTO_LENGTH, &stringOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_create_string_utf8", TAG); return nullptr; } status = napi_set_named_property(env, cJSON_ParseOut, "string", stringOut); if (status != napi_ok) { - getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", tag); + getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); + return nullptr; + } + return cJSON_ParseOut; +} + +// [NAPI_GEN]: introduce function +napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) +{ + // [NAPI_GEN]: get function param in + size_t argc = 1; + napi_value args[1] = {nullptr}; + napi_status status; + const napi_extended_error_info *extended_error_info; + status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_get_cb_info", TAG); + return nullptr; + } + napi_value param0 = args[0]; + char *valueIn0 = getInfo(env, param0); + + // Todo: add business logic. + cJSON *json = cJSON_Parse(valueIn0); + int32_t myInt32Type = static_cast(json->type); + int32_t myInt32Valueint = static_cast(json->valueint); + double myValueDouble = json->valuedouble; + char *valuestring = json->valuestring; + char *string2 = json->string; + if (json->valuestring == NULL) { + valuestring = "json->valuestring is NULL"; + } + if (json->string == NULL) { + string2 = "json->string is NULL"; + } + napi_value nextOut = cJsonParseNextOut(env, json); + napi_value childOut = cJsonParseChildOut(env, json); + napi_value prevOut = cJsonParsePrevOut(env, json); + delete[] valueIn0; + + // [NAPI_GEN]: function return value + napi_value cJSON_ParseOut; + status = napi_create_object(env, &cJSON_ParseOut); + if (status != napi_ok) { + getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", TAG); return nullptr; } + cJSON_ParseOut = getReturnObj(env, cJSON_ParseOut, nextOut,prevOut,childOut, myInt32Type); + cJSON_ParseOut = getReturnObj2(env, cJSON_ParseOut, valuestring, myInt32Valueint, myValueDouble, string2); return cJSON_ParseOut; } diff --git a/examples/napitutorials/tool/commandLine/src/function.json b/examples/napitutorials/tool/commandLine/src/function.json index 58a87b5f..8ff40486 100644 --- a/examples/napitutorials/tool/commandLine/src/function.json +++ b/examples/napitutorials/tool/commandLine/src/function.json @@ -1,7 +1,7 @@ { "directFunction": { "indexTemplete": "export const %s:(%s) => %s;\n", - "cppFuncTemplete": "#include \"napi/native_api.h\"\n#include \n#include \n[include_replace]\n#define GLOBAL_RESMGR (0xFFEE)\nconstexpr int32_t STR_MAX_SIZE = 200;\nconstexpr int32_t LONG_STR_MAX_SIZE = 1024;\nconstexpr int32_t ERR_OK = 0;\nconstexpr int8_t NO_ERROR = 0;\nconstexpr int8_t ERROR = -1;\nconstexpr uint8_t PARAM0 = 0;\nconstexpr uint8_t PARAM1 = 1;\nconstexpr uint8_t PARAM2 = 2;\nconstexpr uint8_t PARAM3 = 3;\nconstexpr uint8_t PARAM4 = 4;\nconstexpr uint8_t PARAM5 = 5;\nconstexpr uint8_t PARAM6 = 6;\nconstexpr uint8_t PARAM7 = 7;\nconstexpr uint8_t PARAM8 = 8;\nconstexpr uint8_t PARAM9 = 9;\nconstexpr uint8_t PARAM10 = 10;\nconstexpr uint8_t PARAM11 = 11;\nconstexpr uint8_t PARAM12 = 12;\nconstexpr uint8_t PARAM100 = 100;\n\nvoid getErrMessage(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info,\n const char *info, const char *tag) {\n status = napi_get_last_error_info(env, &extended_error_info);\n if (status == napi_ok && extended_error_info != NULL) {\n const char *errorMessage =\n extended_error_info->error_message != NULL ? extended_error_info->error_message : \"Unknown error\";\n OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, \"errmsg %{public}s!, engine_err_code %{public}d!.\",\n std::to_string(extended_error_info->engine_error_code).c_str(), extended_error_info->error_code);\n std::string myInfo = info;\n std::string res = \"Failed to \" + myInfo + \" em = \" + errorMessage +\n \", eec = \" + std::to_string(extended_error_info->engine_error_code) +\n \", ec = \" + std::to_string(extended_error_info->error_code);\n napi_throw_error(env, NULL, res.c_str());\n }\n}\n\n[body_replace]\n\nEXTERN_C_START\nstatic napi_value Init(napi_env env, napi_value exports)\n{\n napi_property_descriptor desc[] = {\n [init_replace]\n};\nnapi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);\nreturn exports;\n}\nEXTERN_C_END\n\nstatic napi_module demoModule = {\n .nm_version = 1,\n .nm_flags = 0,\n .nm_filename = nullptr,\n .nm_register_func = Init,\n .nm_modname = \"entry\",\n .nm_priv = ((void*)0),\n .reserved = { 0 },\n};\n\nextern \"C\" __attribute__((constructor)) void RegisterEntryModule(void)\n{\n napi_module_register(&demoModule);\n}", + "cppFuncTemplete": "#include \"napi/native_api.h\"\n#include \n#include \n[include_replace]\n#define GLOBAL_RESMGR (0xFFEE)\nconstexpr int32_t STR_MAX_SIZE = 200;\nconstexpr int32_t LONG_STR_MAX_SIZE = 1024;\nconstexpr int32_t ERR_OK = 0;\nconstexpr int8_t NO_ERROR = 0;\nconstexpr int8_t ERROR = -1;\nconstexpr uint8_t PARAM0 = 0;\nconstexpr uint8_t PARAM1 = 1;\nconstexpr uint8_t PARAM2 = 2;\nconstexpr uint8_t PARAM3 = 3;\nconstexpr uint8_t PARAM4 = 4;\nconstexpr uint8_t PARAM5 = 5;\nconstexpr uint8_t PARAM6 = 6;\nconstexpr uint8_t PARAM7 = 7;\nconstexpr uint8_t PARAM8 = 8;\nconstexpr uint8_t PARAM9 = 9;\nconstexpr uint8_t PARAM10 = 10;\nconstexpr uint8_t PARAM11 = 11;\nconstexpr uint8_t PARAM12 = 12;\nconstexpr uint8_t PARAM100 = 100;\n\nvoid getErrMessage(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info,\n const char *info, const char *tag) {\n status = napi_get_last_error_info(env, &extended_error_info);\n if (status == napi_ok && extended_error_info != NULL)\n{\n const char *errorMessage =\n extended_error_info->error_message != NULL ? extended_error_info->error_message : \"Unknown error\";\n OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, \"errmsg %{public}s!, engine_err_code %{public}d!.\",\n std::to_string(extended_error_info->engine_error_code).c_str(), extended_error_info->error_code);\n std::string myInfo = info;\n std::string res = \"Failed to \" + myInfo + \" em = \" + errorMessage +\n \", eec = \" + std::to_string(extended_error_info->engine_error_code) +\n \", ec = \" + std::to_string(extended_error_info->error_code);\n napi_throw_error(env, NULL, res.c_str());\n }\n}\n\n[body_replace]\n\nEXTERN_C_START\nstatic napi_value Init(napi_env env, napi_value exports)\n{\n napi_property_descriptor desc[] = {\n [init_replace]\n};\nnapi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);\nreturn exports;\n}\nEXTERN_C_END\n\nstatic napi_module demoModule = {\n .nm_version = 1,\n .nm_flags = 0,\n .nm_filename = nullptr,\n .nm_register_func = Init,\n .nm_modname = \"entry\",\n .nm_priv = ((void*)0),\n .reserved = { 0 },\n};\n\nextern \"C\" __attribute__((constructor)) void RegisterEntryModule(void)\n{\n napi_module_register(&demoModule);\n}", "cppFuncDetails": { "funcInitTemplete": "{ \"%s\" , nullptr, %s, nullptr, nullptr, nullptr, napi_default, nullptr },", "funcBodyTemplete": "// [NAPI_GEN]: introduce function\nnapi_value [funcName](napi_env env, napi_callback_info info)\n{\n // [NAPI_GEN]: get function param in\n[func_getParam_replace]\n [func_return_replace]\n}\n", @@ -15,7 +15,7 @@ "int": "", "double": "napi_get_value_double(env, args[%s], &value%s);\n", "bool": "napi_get_value_bool(env, args[%s], &value%s);\n", - "string": "size_t str_size%s = 0;\n status = napi_get_value_string_utf8(env, args[%s], NULL, 0, &str_size%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n return NULL;\n }\n char *%sIn%s = new char[str_size%s + 1];\n status = napi_get_value_string_utf8(env, args[0], %sIn%s, str_size%s + 1, &str_size%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n delete[] %sIn%s;\n return NULL;\n }\n // delete[] %sIn%s; // remember to delete memory \n" + "string": "size_t strSize%s = 0;\n status = napi_get_value_string_utf8(env, args[%s], NULL, 0, &strSize%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n return NULL;\n }\n char *%sIn%s = new char[strSize%s + 1];\n status = napi_get_value_string_utf8(env, args[0], %sIn%s, strSize%s + 1, &strSize%s);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"get value string\", tag);\n delete[] %sIn%s;\n return NULL;\n }\n // delete[] %sIn%s; // remember to delete memory \n" }, "funcReturnType": { "int32_t": " napi_value %sOut;\n status = napi_create_int32(env, 1, &%sOut);\n if (status != napi_ok) {\n getErrMessage(status, env, extended_error_info, \"napi_create_int32\", tag);\n return nullptr;\n }\n", -- Gitee From 4a580dee148c3998bab56412a8bbc82c06011f70 Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 13:43:26 +0800 Subject: [PATCH 3/6] fix: fix codecheck Signed-off-by: gou-jingjing --- .../cpp/ncpp/cjsoncase/cjsonparsecase.cpp | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp index 6680dd57..094d8691 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp @@ -42,7 +42,7 @@ constexpr uint8_t PARAM100 = 100; static const char *TAG = "[KH418_CJSON_Parse]"; void getErrMsgCJSon(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info, - const char *info, const char *tag) + const char *info, const char *tag) { status = napi_get_last_error_info(env, &extended_error_info); if (status == napi_ok && extended_error_info != NULL) { @@ -101,7 +101,7 @@ napi_value getChildTypeOut(napi_env env, napi_value childOut, cJSON *jsonChild) return childOut; } -napi_value getChildStringOut(napi_env env, napi_value childOut, char *stringChild) +napi_value getChildStringOut(napi_env env, napi_value childOut, char *stringChild) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -137,7 +137,7 @@ napi_value getChildValueStringOut(napi_env env, napi_value childOut, char *value return childOut; } -napi_value getChildValueIntOut(napi_env env, napi_value childOut, cJSON *jsonChild) +napi_value getChildValueIntOut(napi_env env, napi_value childOut, cJSON *jsonChild) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -156,7 +156,7 @@ napi_value getChildValueIntOut(napi_env env, napi_value childOut, cJSON *jsonChi return childOut; } -napi_value getChildValueDoubleOut(napi_env env, napi_value childOut, cJSON *jsonChild) +napi_value getChildValueDoubleOut(napi_env env, napi_value childOut, cJSON *jsonChild) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -203,7 +203,7 @@ napi_value cJsonParseChildOut(napi_env env, cJSON *json) return childOut; } -napi_value cJsonParseNextOut(napi_env env, cJSON *json) +napi_value cJsonParseNextOut(napi_env env, cJSON *json) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -257,8 +257,8 @@ char *getInfo(napi_env env, napi_value param0) return valueIn0; } -napi_value getReturnObj(napi_env env, napi_value cJSON_ParseOut, napi_value nextOut, napi_value prevOut, - napi_value childOut, int32_t myInt32Type) +napi_value getReturnObj(napi_env env, napi_value cJSON_ParseOut, napi_value nextOut, napi_value prevOut, + napi_value childOut) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -277,6 +277,14 @@ napi_value getReturnObj(napi_env env, napi_value cJSON_ParseOut, napi_value next getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + + return cJSON_ParseOut; +} + +napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestring, int32_t myInt32Type) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; napi_value typeOut; status = napi_create_int32(env, myInt32Type, &typeOut); if (status != napi_ok) { @@ -288,14 +296,6 @@ napi_value getReturnObj(napi_env env, napi_value cJSON_ParseOut, napi_value next getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } - return cJSON_ParseOut; -} - -napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestring, int32_t myInt32Valueint, - double myValueDouble, char *string2) -{ - napi_status status; - const napi_extended_error_info *extended_error_info; napi_value valuestringOut; status = napi_create_string_utf8(env, valuestring, NAPI_AUTO_LENGTH, &valuestringOut); if (status != napi_ok) { @@ -307,7 +307,13 @@ napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestr getErrMsgCJSon(status, env, extended_error_info, "napi_set_named_property", TAG); return nullptr; } + return cJSON_ParseOut; +} +napi_value getReturnObj3(napi_env env, napi_value cJSON_ParseOut, int32_t myInt32Valueint,double myValueDouble, char *string2) +{ + napi_status status; + const napi_extended_error_info *extended_error_info; napi_value valueintOut; status = napi_create_int32(env, myInt32Valueint, &valueintOut); if (status != napi_ok) { @@ -346,9 +352,8 @@ napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestr return cJSON_ParseOut; } -// [NAPI_GEN]: introduce function -napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) -{ + // [NAPI_GEN]: introduce function + napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) { // [NAPI_GEN]: get function param in size_t argc = 1; napi_value args[1] = {nullptr}; @@ -387,8 +392,9 @@ napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) getErrMsgCJSon(status, env, extended_error_info, "napi_create_object", TAG); return nullptr; } - cJSON_ParseOut = getReturnObj(env, cJSON_ParseOut, nextOut,prevOut,childOut, myInt32Type); - cJSON_ParseOut = getReturnObj2(env, cJSON_ParseOut, valuestring, myInt32Valueint, myValueDouble, string2); + cJSON_ParseOut = getReturnObj(env, cJSON_ParseOut, nextOut, prevOut, childOut); + cJSON_ParseOut = getReturnObj2(env, cJSON_ParseOut, valuestring, myInt32Type); + cJSON_ParseOut = getReturnObj3(env, cJSON_ParseOut, myInt32Valueint, myValueDouble, string2); return cJSON_ParseOut; } -- Gitee From d7430aa6b8bd067d546e01e6d6ee2096500b8dd9 Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 14:13:26 +0800 Subject: [PATCH 4/6] fix: fix codecheck Signed-off-by: gou-jingjing --- .../entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp index 094d8691..dfd49644 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/cjsoncase/cjsonparsecase.cpp @@ -310,7 +310,8 @@ napi_value getReturnObj2(napi_env env, napi_value cJSON_ParseOut, char *valuestr return cJSON_ParseOut; } -napi_value getReturnObj3(napi_env env, napi_value cJSON_ParseOut, int32_t myInt32Valueint,double myValueDouble, char *string2) +napi_value getReturnObj3(napi_env env, napi_value cJSON_ParseOut, int32_t myInt32Valueint, + double myValueDouble, char *string2) { napi_status status; const napi_extended_error_info *extended_error_info; @@ -352,8 +353,9 @@ napi_value getReturnObj3(napi_env env, napi_value cJSON_ParseOut, int32_t myInt3 return cJSON_ParseOut; } - // [NAPI_GEN]: introduce function - napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) { +// [NAPI_GEN]: introduce function +napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) +{ // [NAPI_GEN]: get function param in size_t argc = 1; napi_value args[1] = {nullptr}; -- Gitee From 143e9a6df8befaaa7a121e39833e824345276b0d Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 17:05:30 +0800 Subject: [PATCH 5/6] fix: add comments and cjsonparsecase.cpp.gn Signed-off-by: gou-jingjing --- .../entry/src/main/cpp/cjsonparsecase.cpp.gn | 205 ++++++++++++++++++ .../entry/src/main/cpp/include/nodeapi.h | 2 + .../src/main/cpp/types/libentry/cjson.d.ts | 28 +++ .../src/main/cpp/types/libentry/index.d.ts | 13 +- 4 files changed, 237 insertions(+), 11 deletions(-) create mode 100644 examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn create mode 100644 examples/napitutorials/entry/src/main/cpp/types/libentry/cjson.d.ts diff --git a/examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn b/examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn new file mode 100644 index 00000000..a533c5c4 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn @@ -0,0 +1,205 @@ +#include "napi/native_api.h" +#include +#include +#include + +#define GLOBAL_RESMGR (0xFFEE) +constexpr int32_t STR_MAX_SIZE = 200; +constexpr int32_t LONG_STR_MAX_SIZE = 1024; +constexpr int32_t ERR_OK = 0; +constexpr int8_t NO_ERROR = 0; +constexpr int8_t ERROR = -1; +constexpr uint8_t PARAM0 = 0; +constexpr uint8_t PARAM1 = 1; +constexpr uint8_t PARAM2 = 2; +constexpr uint8_t PARAM3 = 3; +constexpr uint8_t PARAM4 = 4; +constexpr uint8_t PARAM5 = 5; +constexpr uint8_t PARAM6 = 6; +constexpr uint8_t PARAM7 = 7; +constexpr uint8_t PARAM8 = 8; +constexpr uint8_t PARAM9 = 9; +constexpr uint8_t PARAM10 = 10; +constexpr uint8_t PARAM11 = 11; +constexpr uint8_t PARAM12 = 12; +constexpr uint8_t PARAM100 = 100; + +void getErrMessage(napi_status &status, napi_env &env, const napi_extended_error_info *&extended_error_info, + const char *info, const char *tag) { + status = napi_get_last_error_info(env, &extended_error_info); + if (status == napi_ok && extended_error_info != NULL) { + const char *errorMessage = + extended_error_info->error_message != NULL ? extended_error_info->error_message : "Unknown error"; + OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, "errmsg %{public}s!, engine_err_code %{public}d!.", + std::to_string(extended_error_info->engine_error_code).c_str(), extended_error_info->error_code); + std::string myInfo = info; + std::string res = "Failed to " + myInfo + " em = " + errorMessage + + ", eec = " + std::to_string(extended_error_info->engine_error_code) + + ", ec = " + std::to_string(extended_error_info->error_code); + napi_throw_error(env, NULL, res.c_str()); + } +} + +// [NAPI_GEN]: introduce function +napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info) +{ + // [NAPI_GEN]: get function param in + size_t argc = 1; + napi_value args[1] = {nullptr}; + napi_status status; + const napi_extended_error_info *extended_error_info; + const char * tag = "[KH418_CJSON_Parse]"; + status = napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + if(status != napi_ok) { + getErrMessage(status, env,extended_error_info, "napi_get_cb_info",tag); + return nullptr; + } + napi_valuetype valuetype0; + status = napi_typeof(env, args[0], &valuetype0); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_typeof", tag); + return nullptr; + } + size_t str_size0 = 0; + status = napi_get_value_string_utf8(env, args[0], NULL, 0, &str_size0); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "get value string", tag); + return NULL; + } + char *valueIn0 = new char[str_size0 + 1]; + status = napi_get_value_string_utf8(env, args[0], valueIn0, str_size0 + 1, &str_size0); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "get value string", tag); + delete[] valueIn0; + return NULL; + } + // delete[] valueIn0; // remember to delete memory + + + // Todo: add business logic. + + // [NAPI_GEN]: function return value + napi_value cJSON_ParseOut; + status = napi_create_object(env, &cJSON_ParseOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + napi_value nextOut; + status = napi_create_object(env, &nextOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "next", nextOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value prevOut; + status = napi_create_object(env, &prevOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "prev", prevOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value childOut; + status = napi_create_object(env, &childOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_object", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "child", childOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value typeOut; + status = napi_create_int32(env, 1, &typeOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "type", typeOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valuestringOut; + status = napi_create_string_utf8(env, "valuestring", NAPI_AUTO_LENGTH, &valuestringOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valuestring", valuestringOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valueintOut; + status = napi_create_int32(env, 1, &valueintOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_int32", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valueint", valueintOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value valuedoubleOut; + status = napi_create_double(env, 1.0, &valuedoubleOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_double", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "valuedouble", valuedoubleOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + napi_value stringOut; + status = napi_create_string_utf8(env, "string", NAPI_AUTO_LENGTH, &stringOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_create_string_utf8", tag); + return nullptr; + } + status = napi_set_named_property(env, cJSON_ParseOut, "string", stringOut); + if (status != napi_ok) { + getErrMessage(status, env, extended_error_info, "napi_set_named_property", tag); + return nullptr; + } + + return cJSON_ParseOut; +} + + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + { "KH418_CJSON_Parse" , nullptr, KH418_CJSON_Parse, 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); +} \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h index 9e470419..671fd956 100644 --- a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h +++ b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h @@ -32,6 +32,8 @@ napi_value setThreadsafefuncrel(napi_env env, napi_callback_info info); napi_value setThreadsafefuncall(napi_env env, napi_callback_info info); napi_value cJSONVersion(napi_env env, napi_callback_info info); + +// cJSON.h: CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); napiܴ napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info); #endif //NAPITUTORIALS_NODEAPI_H diff --git a/examples/napitutorials/entry/src/main/cpp/types/libentry/cjson.d.ts b/examples/napitutorials/entry/src/main/cpp/types/libentry/cjson.d.ts new file mode 100644 index 00000000..32ccc556 --- /dev/null +++ b/examples/napitutorials/entry/src/main/cpp/types/libentry/cjson.d.ts @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development 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. +*/ + +// 对应cJSON.h中: typedef struct cJSON {} +export interface cJSON { + next: cJSON; + prev: cJSON; + child: cJSON; + type: number; + valuestring: string; + valueint: number; + valuedouble: number; + string: string; +} +// 对应cJSON.h中: CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); 方法的dts接口 +export const KH418_cJSON_Parse:(value: string) => cJSON; \ No newline at end of file diff --git a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts index 6561fd9d..6ec3034f 100644 --- a/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts +++ b/examples/napitutorials/entry/src/main/cpp/types/libentry/index.d.ts @@ -13,6 +13,8 @@ * limitations under the License. */ +import {cJSON, KH418_cJSON_Parse} from './cjson' + export interface InstanceData { testint32: number; } @@ -45,17 +47,6 @@ export const testNapiGetElement: (a: object, b: number) => string; export const testNapiHasElement: (a: object, b: number) => string; export const testNapiDeleteElement: (a: object, b: number) => string; -export interface cJSON { - next: cJSON; - prev: cJSON; - child: cJSON; - type: number; - valuestring: string; - valueint: number; - valuedouble: number; - string: string; -} -export const KH418_cJSON_Parse:(value: string) => cJSON; /* work_with_javascript_values_and_abstract_operations */ export const testNapiCoerceToBool: (a: any) => boolean; -- Gitee From 811d7758a4870112d1e6a4608a0640bf895035a5 Mon Sep 17 00:00:00 2001 From: gou-jingjing Date: Mon, 15 Apr 2024 18:57:15 +0800 Subject: [PATCH 6/6] fix: fix codecheck Signed-off-by: gou-jingjing --- .../main/cpp/{cjsonparsecase.cpp.gn => cjsonparsecase.cpp.gen} | 0 examples/napitutorials/entry/src/main/cpp/include/nodeapi.h | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename examples/napitutorials/entry/src/main/cpp/{cjsonparsecase.cpp.gn => cjsonparsecase.cpp.gen} (100%) diff --git a/examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn b/examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gen similarity index 100% rename from examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gn rename to examples/napitutorials/entry/src/main/cpp/cjsonparsecase.cpp.gen diff --git a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h index 671fd956..ee32fd1b 100644 --- a/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h +++ b/examples/napitutorials/entry/src/main/cpp/include/nodeapi.h @@ -33,7 +33,7 @@ napi_value setThreadsafefuncall(napi_env env, napi_callback_info info); napi_value cJSONVersion(napi_env env, napi_callback_info info); -// cJSON.h: CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); napiܴ +// cJSON.h中: CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); 方法的napi框架代码用例 napi_value KH418_CJSON_Parse(napi_env env, napi_callback_info info); #endif //NAPITUTORIALS_NODEAPI_H -- Gitee