pmed / v8pp

Bind C++ functions and classes into V8 JavaScript engine
http://pmed.github.io/v8pp/
Other
886 stars 118 forks source link

`char[]` type problem. #174

Closed Aincvy closed 2 years ago

Aincvy commented 2 years ago

Here is some code.

union SightNodeValue{
    int i;
    float f;
    double d;
    bool b;
    char string[NAME_BUF_SIZE] = {0};
    char* largeString;     // todo largeString
};

void test(){
  functionObject->Set(context, v8pp::to_v8(isolate, "value"), v8pp::to_v8(isolate, item.value.string));
}

The stmt v8pp::to_v8(isolate, item.value.string)) will call this function.

template<size_t N>
v8::Local<v8::String> to_v8(v8::Isolate* isolate,
    char const (&str)[N], size_t len = N - 1)
{
    return convert<string_view>::to_v8(isolate, string_view(str, len));
}

Then my string has a lot of 0, and those 0 will be a part of a string. Here is some log.

[..t/sight/sight_js.cpp:997 (parseGraph)] finalSource = "varName = 23.5 + -69.5;" (std::string)
[..t/sight/sight_js.cpp:997 (parseGraph)] finalSource.length() = 80 (unsigned long)
[..t/sight/sight_js.cpp:997 (parseGraph)] finalSource.size() = 80 (unsigned long)
[..t/sight/sight_js.cpp:998 (parseGraph)] finalSource.data() = varName (char*)
[..t/sight/sight_js.cpp:999 (parseGraph)] finalSource.c_str() = "varName" (const char*)
varName
11897114789710910100000000000000000000000000000000000000000000000000000000032613250514653324332455457465359

The (last line of log)'s code is:

for (const auto &item : finalSource) {
    printf("%d",item);
}
printf("\n");

When I change the code to functionObject->Set(context, v8pp::to_v8(isolate, "value"), v8pp::to_v8(isolate, (const char*) item.value.string));. It works fine, those 0 are gone.

I use char[] as a string buffer.

I don't know this is a design or not.

pmed commented 2 years ago

Hi,

to_v8() works as expected:

You can use the 2nd argument of to_v8(str, len) to specify the desired string length for such a fixed size arrays.