我正在使用 c++ 和 v8,并且遇到了以下挑战:我希望能够使用 v8 在 javascript 中定义一个函数,然后稍后通过 c++ 调用该函数。此外,我希望能够将参数从 c++ 传递给 javascript 函数。我认为下面的示例源代码可以最好地解释它。检查示例代码的末尾,看看我想要完成什么。
#include <v8.h>
#include <iostream>
#include <string>
#include <array>
using namespace v8;
int main(int argc, char* argv[]) {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Persistent<Context> context = Context::New();
Context::Scope context_scope(context);
Handle<String> source;
Handle<Script> script;
Handle<Value> result;
// Create a string containing the JavaScript source code.
source = String::New("function test_function(test_arg) { var match = 0;if(test_arg[0] == test_arg[1]) { match = 1; }");
// Compile the source code.
script = Script::Compile(source);
// What I want to be able to do (this part isn't valid code..
// it just represents what I would like to do.
// An array is defined in c++ called pass_arg,
// then passed to the javascript function test_function() as an argument
std::array< std::string, 2 > pass_arg = {"value1", "value2"};
int result = script->callFunction("test_function", pass_arg);
}
有小费吗?
更新:
根据给出的建议,我已经能够整理出以下代码。它已经过测试并且可以工作:
#include <v8.h>
#include <iostream>
#include <string>
using namespace v8;
int main(int argc, char* argv[]) {
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Persistent<Context> context = Context::New();
//context->AllowCodeGenerationFromStrings(true);
// Enter the created context for compiling and
// running the hello world script.
Context::Scope context_scope(context);
Handle<String> source;
Handle<Script> script;
Handle<Value> result;
// Create a string containing the JavaScript source code.
source = String::New("function test_function() { var match = 0;if(arguments[0] == arguments[1]) { match = 1; } return match; }");
// Compile the source code.
script = Script::Compile(source);
// Run the script to get the result.
result = script->Run();
// Dispose the persistent context.
context.Dispose();
// Convert the result to an ASCII string and print it.
//String::AsciiValue ascii(result);
//printf("%s\n", *ascii);
Handle<v8::Object> global = context->Global();
Handle<v8::Value> value = global->Get(String::New("test_function"));
Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
Handle<Value> args[2];
Handle<Value> js_result;
int final_result;
args[0] = v8::String::New("1");
args[1] = v8::String::New("1");
js_result = func->Call(global, 2, args);
String::AsciiValue ascii(js_result);
final_result = atoi(*ascii);
if(final_result == 1) {
std::cout << "Matched\n";
} else {
std::cout << "NOT Matched\n";
}
return 0;
}