我正在尝试使c ++代码中定义的某些功能可用于在v8上运行的JavaScript代码。
在网络上找到了一些示例之后,我被认为可以使用以下示例:
#include <stdio.h>
#include <v8.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
v8::Handle< v8::Value > print( const v8::Arguments & args ) {
for ( int i = 0; i < args.Length(); i++ )
{
v8::String::Utf8Value str( args[ i ] );
std::cout << *str;
}
return v8::Undefined();
}
int main( int argc, char* argv[] ) {
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope;
// Make "print" available:
v8::Handle< v8::ObjectTemplate > global = v8::ObjectTemplate::New();
global->Set( v8::String::New( "print" ), v8::FunctionTemplate::New( print ) );
// Create a new context.
v8::Handle< v8::Context > context = v8::Context::New();
// Enter the created context for compiling and
// running the hello world script.
v8::Context::Scope context_scope( context );
// Create a string containing the JavaScript source code.
v8::Handle< v8::String > source = v8::String::New(
"\
print( 'Hello' );\
'Hello' + ', World!'\
"
);
// Compile the source code.
v8::Handle< v8::Script > script = v8::Script::Compile( source );
// Run the script to get the result.
v8::Handle< v8::Value > result = script->Run();
return 0;
}
它确实可以很好地编译,但是当我运行已编译的程序时,总是出现错误:
<unknown>:6: Uncaught ReferenceError: print is not defined
我做错了什么?
缺少的是您对设置的global
模板没有做任何事情。如果查看可以传递给Context::New
的参数,您会发现可以为其中的全局对象指定对象模板:
v8::Context::New(isolate, nullptr, global);
您还应该设置一个Isolate
(在此处作为isolate
传递);实际上,v8::HandleScope handle_scope;
甚至在没有当前版本的情况下甚至都不应该编译。
有关详细信息,请参阅官方文档,其中对此进行了解释以及许多其他内容:https://v8.dev/docs/embed