在 V8 中创建自定义 JavaScript 函数?
Creating custom JavaScript functions in V8?
我正在尝试将一个自定义函数嵌入到我的项目中,该项目使用 V8 引擎,但显然我无法使其正常工作。我使用过我发现的代码,但它似乎已经过时,或者我只是做错了。我的观点是包含一个自定义 javascript 文件。我当前的代码(用于测试)是这样的:
HandleScope handle_scope(isolate);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
global->Set(v8::String::NewFromUtf8(isolate, "test", v8::NewStringType::kNormal).ToLocalChecked(),
v8::FunctionTemplate::New(isolate, test));
Handle<Context> context = Context::New(isolate);
Persistent<Context> persistent_context(isolate, context);
Context::Scope context_scope(context);
const char* data = "test";
Handle<String> source = String::NewFromUtf8(isolate, data);
Handle<Script> script = Script::Compile(source);
if (!script.IsEmpty())
Handle<Value> result = script->Run();
测试代码(显然只是为了测试):
void test(const v8::FunctionCallbackInfo<v8::Value>& args) {
MessageBoxA(NULL,"test", "", 0);
}
但是引擎returns这个错误:
Uncaught ReferenceError: test is not defined
所以我的问题是,如果我做对了,我希望能够包含我自己,但我就是无法执行函数。
下面是一些有效项目的代码:
Isolate::Scope iscope( isolate_ );
HandleScope hs( isolate_ );
Local<Object> test = Object::New(isolate_);
test->Set(String::NewFromUtf8(isolate_, "javaScriptFunctionName"), Function::New(isolate_, CPP_FN_CALLBACK));
global_template->Set(String::NewFromUtf8(isolate_, "test"), test);
这将导致 window.test
的对象具有名为 window.test.javaScriptFunctionName()
的函数
我正在尝试将一个自定义函数嵌入到我的项目中,该项目使用 V8 引擎,但显然我无法使其正常工作。我使用过我发现的代码,但它似乎已经过时,或者我只是做错了。我的观点是包含一个自定义 javascript 文件。我当前的代码(用于测试)是这样的:
HandleScope handle_scope(isolate);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
global->Set(v8::String::NewFromUtf8(isolate, "test", v8::NewStringType::kNormal).ToLocalChecked(),
v8::FunctionTemplate::New(isolate, test));
Handle<Context> context = Context::New(isolate);
Persistent<Context> persistent_context(isolate, context);
Context::Scope context_scope(context);
const char* data = "test";
Handle<String> source = String::NewFromUtf8(isolate, data);
Handle<Script> script = Script::Compile(source);
if (!script.IsEmpty())
Handle<Value> result = script->Run();
测试代码(显然只是为了测试):
void test(const v8::FunctionCallbackInfo<v8::Value>& args) {
MessageBoxA(NULL,"test", "", 0);
}
但是引擎returns这个错误:
Uncaught ReferenceError: test is not defined
所以我的问题是,如果我做对了,我希望能够包含我自己,但我就是无法执行函数。
下面是一些有效项目的代码:
Isolate::Scope iscope( isolate_ );
HandleScope hs( isolate_ );
Local<Object> test = Object::New(isolate_);
test->Set(String::NewFromUtf8(isolate_, "javaScriptFunctionName"), Function::New(isolate_, CPP_FN_CALLBACK));
global_template->Set(String::NewFromUtf8(isolate_, "test"), test);
这将导致 window.test
的对象具有名为 window.test.javaScriptFunctionName()