v8 C++ Api:将非英语字符串从 JavaScript 传递给 c++
v8 C++ Api: pass non-English strings from JavaScript to c++
在我的 C++ 代码中我有:
Handle<ObjectTemplate> globalTemplate = ObjectTemplate::New();
globalTemplate->Set( String::New("print"), FunctionTemplate::New( printMessage ));
Handle<Context> context = Context::New( NULL, globalTemplate );
printMessage 函数定义为:
Handle<Value> printMessage(const Arguments& args)
{
Locker locker;
HandleScope scope;
if( args.Length() )
{
String::Utf8Value message( args[0]->ToString() );
if( message.length() )
{
//Print the message to stdout
printf( "%s", *message );
bool newline = true;
if(args.Length() == 2)
{
newline = args[1]->ToBoolean()->BooleanValue();
}
if(newline) printf("\n");
return scope.Close( Boolean::New( true ) );
}
}
return Undefined();
}
当我从 JavaScript 调用此函数时:
print("Привет");
我看到“пїЅпїЅпїЅпїЅпїЅпїЅ”而不是字符串。
这段代码有什么问题?
代码看起来是正确的,正如@xaxxon 所建议的,我会仔细检查您用于输出的终端是否可以处理非 ASCII 字符,以及输入文件(如果有)的编码是否正确。
此外,您的 V8 版本似乎很旧(例如 HandleScope
构造函数现在总是采用 Isolate*
参数),因此您也可能遇到了一些旧错误已修复。
作为参考,official sample shell 以几乎相同的方式做事,并且在我的机器上至少可以正常使用您的测试字符串:
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
bool first = true;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(args[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
}
printf("\n");
fflush(stdout);
}
在我的 C++ 代码中我有:
Handle<ObjectTemplate> globalTemplate = ObjectTemplate::New();
globalTemplate->Set( String::New("print"), FunctionTemplate::New( printMessage ));
Handle<Context> context = Context::New( NULL, globalTemplate );
printMessage 函数定义为:
Handle<Value> printMessage(const Arguments& args)
{
Locker locker;
HandleScope scope;
if( args.Length() )
{
String::Utf8Value message( args[0]->ToString() );
if( message.length() )
{
//Print the message to stdout
printf( "%s", *message );
bool newline = true;
if(args.Length() == 2)
{
newline = args[1]->ToBoolean()->BooleanValue();
}
if(newline) printf("\n");
return scope.Close( Boolean::New( true ) );
}
}
return Undefined();
}
当我从 JavaScript 调用此函数时:
print("Привет");
我看到“пїЅпїЅпїЅпїЅпїЅпїЅ”而不是字符串。
这段代码有什么问题?
代码看起来是正确的,正如@xaxxon 所建议的,我会仔细检查您用于输出的终端是否可以处理非 ASCII 字符,以及输入文件(如果有)的编码是否正确。
此外,您的 V8 版本似乎很旧(例如 HandleScope
构造函数现在总是采用 Isolate*
参数),因此您也可能遇到了一些旧错误已修复。
作为参考,official sample shell 以几乎相同的方式做事,并且在我的机器上至少可以正常使用您的测试字符串:
void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
bool first = true;
for (int i = 0; i < args.Length(); i++) {
v8::HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" ");
}
v8::String::Utf8Value str(args[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
}
printf("\n");
fflush(stdout);
}