如何从Node.js调用C ++代码?

时间:2012-09-16 14:00:38

标签: c++ node.js performance v8 ffi

我目前正在开发一个在服务器上运行的模拟器,它应该在浏览器中显示数据。

对于提供文件,通信和类似的东西,我想使用Node.js.但是,我不确定它是否会在计算部门中表现得如此好,所以我想用C ++开发模拟部分。

模拟分为单独的“世界”,所有这些都以一些初始参数开始。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:35)

好吧,V8允许从JavaScript调用C ++代码。

所以你可以拥有3部分代码:

  • 普通C ++,不知道node.js和V8。这将是World的位置。
  • Glue node.js / V8-C ++代码,允许JS“看到”World类的部分内容。
  • 普通JavaScript代码,通过“胶水”层与C ++端进行通信

首先,了解V8和C ++如何通信。 Google提供了相关指南:https://developers.google.com/v8/embed

然后,你需要node.js特定的胶水。请参阅http://www.slideshare.net/nsm.nikhil/writing-native-bindings-to-nodejs-in-chttp://syskall.com/how-to-write-your-own-native-nodejs-extension

从上面的slidehare链接:

#include <v8.h>
#include <node.h>

using namespace v8;

extern "C" {
   static void init(Handle<Object> target) {}
   NODE_MODULE(module_name, init)
}

我们可以将其扩展到更接近您想要的东西:

的src / world.h

#ifndef WORLD_H_
#define WORLD_H_

class World {
    public:
        void update();
};

extern World MyWorld;

#endif

的src / world.cpp

#include "world.h"
#include <iostream>

using std::cout;
using std::endl;

World MyWorld;

void World::update() {
    cout << "Updating World" << endl;
}

的src / bind.cpp

#include <v8.h>
#include <node.h>
#include "world.h"

using namespace v8;

static Handle<Value> UpdateBinding(const Arguments& args) {
    HandleScope scope;

    MyWorld.update();

    return Undefined();
}

static Persistent<FunctionTemplate> updateFunction;

extern "C" {
   static void init(Handle<Object> obj) {
      v8::HandleScope scope;

        Local<FunctionTemplate> updateTemplate = FunctionTemplate::New(UpdateBinding);

        updateFunction = v8::Persistent<FunctionTemplate>::New(updateTemplate);

      obj->Set(String::NewSymbol("update"), updateFunction->GetFunction());
   }

   NODE_MODULE(world, init)
}

演示/ demo.js

var world = require('../build/Release/world.node');
world.update();

WScript的

def set_options(opt):
  opt.tool_options("compiler_cxx")

def configure(conf):
  conf.check_tool("compiler_cxx")
  conf.check_tool("node_addon")

def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon") 
  obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"]
  # This is the name of our extension.
  obj.target = "world"
  obj.source = "src/world.cpp src/bind.cpp"
  obj.uselib = []

在Linux shell上,有些设置:

node-waf configure

要构建,请运行:

node-waf

测试:

node demo/demo.js

输出:

Updating World