Reputation: 476
I am trying to wrap V8 in a class structure where there exists one object that exposes JavaScript callbacks to the C++ code, which should do some data handling.
The idea was to keep context and handle_scope available to all participating class, i.e. i thought of a 'global' state. I boiled it down to the following example:
using namespace v8;
Persistent<Context> context;
HandleScope handle_scope;
struct CallBackTest {
HandleScope handle_scope;
Handle<v8::Function> function;
void RegisterCallback(Handle<v8::Function> f) {
function = f;
}
bool MakeCall(int argc, Handle<Value> args[2]) {
Handle<Value> js_result = function->Call(context->Global(), argc, args);
String::AsciiValue ascii(js_result);
return atoi(*ascii);
}
};
struct V8Wrapper {
CallBackTest tester;
V8Wrapper() {
context = Context::New();
Context::Scope context_scope(context);
Handle<String> source;
Handle<Script> script;
Handle<Value> result;
source = String::New("function test_function() { return (arguments[0] == arguments[1]); };");
script = Script::Compile(source);
result = script->Run();
Handle<v8::Value> value1 = context->Global()->Get(String::New("test_function"));
if(!value1->IsFunction()) {
std::cout << "function not found" << std::endl;
} else {
Handle<v8::Function> func1 = v8::Handle<v8::Function>::Cast(value1);
tester.RegisterCallback(func1);
}
}
};
int main(int argc, char* argv[]) {
V8Wrapper wrap;
Handle<Value> args[2];
Handle<Value> js_result;
int final_result;
args[0] = v8::String::New("1");
args[1] = v8::String::New("1");
final_result = wrap.tester.MakeCall(2, args);
if(final_result == 1) {
std::cout << "Matched\n";
} else {
std::cout << "NOT Matched\n";
}
}
Thanks.
Upvotes: 1
Views: 793
Reputation: 68
I think your problem is a misunderstanding with the HandleScope. A Handle must "live" inside of a scope in which a HandleScope has been defined. The idea of HandleScope is not that of a global structure which must be defined in some global place but rather corresponds to a stack-like concept.
Upvotes: 1