Symptom
The char array contains only part of the string passed from ArkTS.
Possible Causes
Cause 1: The length of the char array is less than the length of the string.
Cause 2: When napi_get_value_string_utf8() is used to obtain the string passed from ArkTS, the value of the fourth parameter is less than the length of the string passed from ArkTS.
Solution
Assume that the ArkTS string stored in info is abcdefghigk.
Cause 1: The length of the char array is insufficient.
static napi_value TestFunc(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
size_t len = 0;
char buf[5]; // Allocate a char array of length 5
napi_get_value_string_utf8(env, args[0], buf, 1024, &len); // Get string, buf result is' abcde '
// ...
} The string abcdefghigk is truncated to abcde because the length of the char array is 5. To solve this problem, modify the value of char buf.
Cause 2: When napi_get_value_string_utf8() is used to obtain the string passed from ArkTS, the value of the fourth parameter is less than the length of the string passed from ArkTS.
static napi_value TestFunc(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
size_t len = 0;
char buf[1024];
napi_get_value_string_utf8(env, args[0], buf, 5, &len); // Get string, buf result is' abcde '
// ...
} The string abcdefghigk is truncated to abcd because the value of the fourth parameter is 5 and the terminator '\0' occupies one character space.
To solve this problem, ensure that the length of the char array is greater than or equal to the length of the string and the value of the fourth parameter in napi_get_value_string_utf8() is greater than the length of the string. Specifically, use napi_get_value_string_utf8 to obtain the length of the string, and allocate the memory space for the char array based on the length obtained. When allocating the memory, increase the length by 1 to reserve a bit for the terminator '\0' of the string.
Sample code:
napi_value Test::TestFunc(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value args[1] = {nullptr};
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
size_t len = 0;
napi_get_value_string_utf8(env, args[0], nullptr, 0, &len); // Get string length to len
char *buf = new char[len + 1]; // Allocate a char array of appropriate size
napi_get_value_string_utf8(env, args[0], buf, len + 1, &len); // get string
OH_LOG_ERROR(LOG_APP, "result is: b:%{public}s.", buf);
return nullptr;
}