Question
Solution
The third parameter of OH_JSVM_GetValueStringUtf8 is the memory address to which the string is written. If a null pointer is passed in, the interface returns the length of the string (excluding the terminator) through the last parameter result.
JSVM_EXTERN JSVM_Status OH_JSVM_GetValueStringUtf8(JSVM_Env env,
JSVM_Value value,
char* buf,
size_t bufsize,
size_t* result); To obtain a string, perform the following steps:
std::string GetValueString(JSVM_Env env, JSVM_Value value) {
constexpr size_t PREALLOC_SIZE = 256;
char preallocMemory[PREALLOC_SIZE];
char *buff = preallocMemory;
// Obtain length
size_t totalLen = 0;
OH_JSVM_GetValueStringUtf8(env, value, nullptr, 0, &totalLen);
size_t needed = totalLen + 1;
if (needed > PREALLOC_SIZE) {
// Allocate space, size must include termination character
buff = new char[needed];
}
// get string
OH_JSVM_GetValueStringUtf8(env, value, buff, needed, nullptr);
std::string ret(buff, totalLen);
if (needed > PREALLOC_SIZE) {
delete[] buff;
}
return ret;
}