Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WriteUtf8行为和v8保持一致 #14

Closed
chexiongsheng opened this issue Apr 11, 2024 · 2 comments
Closed

WriteUtf8行为和v8保持一致 #14

chexiongsheng opened this issue Apr 11, 2024 · 2 comments

Comments

@chexiongsheng
Copy link
Contributor

static void Print(const v8::FunctionCallbackInfo<v8::Value>& info) {
    //std::cout << "Print:" << info.Length() << std::endl;
    v8::Isolate* isolate = info.GetIsolate();
    v8::Local<v8::Context> context = isolate->GetCurrentContext();
    
    //std::cout << "len:" << info.Length() << std::endl;
    
    auto str = info[0]->ToString(context).ToLocalChecked();
    
    auto len = str->Utf8Length(isolate);
    //std::cout << "len:" << len << std::endl;
    UE_LOG(LogTemp, Warning, TEXT("len: %d"), len);
    char* data = new char[len + 1];
    data[len] = 111;
    str->WriteUtf8(isolate, data);
    //std::cout << "data[n]:" << (int)data[len] << std::endl;
    UE_LOG(LogTemp, Warning, TEXT("data[n]: %d"), (int)data[len]);
    
    std::string msg = *(v8::String::Utf8Value(isolate, str));
    //std::cout << msg << std::endl;
}

如上代码,用typescirpt调用

globalThis.Print('hello');

用v8时打印

LogTemp: Warning: len: 5
LogTemp: Warning: data[n]: 0

用backend-quickjs时打印

LogTemp: Warning: len: 5
LogTemp: Warning: data[n]: 111

简单来说v8会认为内存分配为Utf8Length + 1,并自动在str[Utf8Length] 添加0结尾。

@chexiongsheng
Copy link
Contributor Author

这点差异导致某项目崩溃,该项目本来希望通过puerts那加修复:Tencent/puerts#1680
但这是应该属于backend-quickjs的bug

@chexiongsheng
Copy link
Contributor Author

chexiongsheng commented Apr 11, 2024

我看unity还是挺多地方用到WriteUtf8,比如这里:https://github.com/Tencent/puerts/blob/2881eace91871eb0ce6b164077ea344aa02ea8fa/unity/native_src/Src/PluginImpl.cpp#L433

不过这里带了长度了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant