目录

How do I use OH_JSVM_GetValueStringUtf8 to obtain a string?

Question

  1. The size of the buffer passed in OH_JSVM_GetValueStringUtf8 is uncertain.
  2. Using OH_JSVM_GetValueStringUtf8 to obtain an overlong string may cause a crash.

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:

  1. Call OH_JSVM_GetValueStringUtf8 to obtain the length of the string.
  2. Request memory for the buffer.
  3. Call OH_JSVM_GetValueStringUtf8 to obtain the string.
    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;
    }
  1. The allocated buffer size must be greater than the string length because the string length does not contain the last termination character. If the buffer size is equal to the string length, the last character of the string will be overwritten by the termination character.
  2. You are advised not to allocate space using char buff[totalLen + 1] on the stack. If the string is too long, stack overflow may occur, causing application breakdown.