综合开发

Javascript equivalents in V8?

微信扫一扫,分享到朋友圈

Javascript equivalents in V8?

I’m playing with NodeJS and V8 in an attempt to learn both.

I’d like to translate this simple JS line in C++.

global.Game = { sleep: call_some_CPP_function };

For the past two days, I’ve been piecing together code found on the Internet and in other people’s source code, trying to understand how it works, except I didn’t end up with much.

The code below doesn’t work, if I do a console.log(global.Game)
, I get nothing.

#include "node.h"
#include "v8.h"
namespace node{
using namespace v8; // make life easier
// define a sleepy thread blocker
Handle<Value> call_some_CPP_function(const FunctionCallbackInfo<Value>& a){
HandleScope scope(node_isolate);
Sleep(3);
return scope.Close(Undefined());
}
// let's create the object here
// I'm calling this function elsewhere
void execme(){
// I've read somewhere that I have to do this
Locker locker(node_isolate);
HandleScope scope(node_isolate);
// I think these two set the execution context (variables) and "this" accordingly
// but I'm not sure
Local<Context> context = node_isolate->GetCurrentContext();
Context::Scope context_scope(context);
// I need a reference to the global object, to assign my "Game" object
Local<Object> global = node_env->context()->Global();
// The only way is to invent a constructor for it
Local<FunctionTemplate> function_template = FunctionTemplate::New();
function_template->SetClassName(String::New("GameClass"));
// and create a new instance using that constructor
Local<Object> game_object = function_template->GetFunction()->NewInstance();
// after that, add the "sleep" function, which executes the function above
NODE_SET_METHOD(game_object, "sleep", call_some_CPP_function);
// and finally do the global.Game assignment
global->Set(String::New("Game"), game_object);
}
}

Problem courtesy of: Silviu-Marian

Solution

game.cc

#include <node.h>
#include <v8.h>
using namespace v8;
// sleep 3 seconds
Handle<Value> Sleep(const Arguments& args) {
HandleScope scope;
Sleep(3000);
return scope.Close(Undefined());
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("sleep"),
FunctionTemplate::New(Sleep)->GetFunction());
}
NODE_MODULE(game, init)

app.js

global.Game = require('./build/Release/game');
console.log(global.Game); // this will print "{ sleep: [Function] }"
//now you can call native sleep
Game.sleep();

Document: http://nodejs.org/api/addons.html#addons_hello_world

Solution courtesy of: damphat

微信扫一扫,分享到朋友圈

Javascript equivalents in V8?

Get a basic chat application working with WebRTC

上一篇

达美航空CEO:下个月起将“完全实现碳中和”

下一篇

你也可能喜欢

评论已经被关闭。

插入图片

热门栏目

Javascript equivalents in V8?

长按储存图像,分享给朋友