V8 中的 Javascript 等价物?

标签 javascript c++ node.js v8

我正在使用 NodeJS 和 V8,试图学习两者。

我想用 C++ 翻译这个简单的 JS 行。

global.Game = { sleep: call_some_CPP_function }; 

在过去的两天里,我一直在拼凑在互联网上和其他人的源代码中找到的代码,试图理解它是如何工作的,但最终我并没有得到太多结果。

下面的代码不起作用,如果我执行 console.log(global.Game),我什么也得不到。

#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);
    }

}

最佳答案

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();

文档:http://nodejs.org/api/addons.html#addons_hello_world

关于V8 中的 Javascript 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21322185/

相关文章:

javascript - typescript 字符串 | string[] 求数组长度

javascript - 如何使div中的按钮转到新的div

Javascript 解压命令行字典

node.js - 在 index.html 中加载 angular app-root 时未显示 mat-spinner

angularjs - 如何使用用户名查询 Mongoose

node.js - 部署到 Google App Engine 时出错

javascript - 颜色选择器 Farbtastic 在 2 个类上同步

c++ - 错误 : ‘template’ (as a disambiguator) is only allowed within templates

c++ - 为什么我将函数命名为 `swap` 时会出现模板错误,但 `Swap` 没问题?

c++ - 如何确定 Pango 的后备字体?