如何将wchar_t转换为V8字符串?

时间:2019-09-24 16:02:39

标签: c++ node.js

我想在节点插件中返回wchar_t数组。如何转换wchar_t数组,以便V8引擎接受它?

// This is the normal way i return an string back to javascript
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "MY_TEXT", NewStringType::kNormal).ToLocalChecked());

// This is my code where i want to return the "textBuffer" back to Javascript.

void Method(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    ...

    const int bufferSize = 1024;
    wchar_t textBuffer[bufferSize];
    int copied = SendMessage(hwndEdit, WM_GETTEXT, (WPARAM)bufferSize, (LPARAM)textBuffer);
    printf("Copied %d chars.\n", copied);
    printf("getting text:\n");
    //wprintf(L"%ls \n", textBuffer);

    // RETURN THE textBuffer as STRING HERE

    //args.GetReturnValue().Set( HERE );
    //args.GetReturnValue().Set(String::NewFromUtf8(isolate, "test", NewStringType::kNormal).ToLocalChecked());

}

1 个答案:

答案 0 :(得分:2)

以下代码会将wchar_t字符串转换为UTF-8字符串。请注意,尽管std::codecvt自C ++ 17起已被弃用(尽管没有足够的替代方法)。

#include <string>
#include <codecvt>
#include <locale>

std::string ws_to_UTF8 (const wchar_t *ws)
{
    std::wstring_convert <std::codecvt_utf8 <wchar_t>, wchar_t> convert;
    return convert.to_bytes (ws);
}

然后您可以在返回的字符串上调用c_str (),以获取C样式的UTF8字符串传递给args.GetReturnValue().Set ()