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

cor*_*zza 15 c++ performance v8 ffi node.js

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

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

模拟分为单独的"世界",它们都以一些初始参数开始.

做这个的最好方式是什么?

lui*_*bal 35

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

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

  • 普通的C++,不知道node.js和V8.这将是在哪里World.
  • 粘贴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 -延期

从上面的slidehare链接:

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

using namespace v8;

extern "C" {
   static void init(Handle<Object> target) {}
   NODE_MODULE(module_name, init)
}
Run Code Online (Sandbox Code Playgroud)

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

SRC/world.h

#ifndef WORLD_H_
#define WORLD_H_

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

extern World MyWorld;

#endif
Run Code Online (Sandbox Code Playgroud)

SRC/world.cpp

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

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

World MyWorld;

void World::update() {
    cout << "Updating World" << endl;
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

演示/ demo.js

var world = require('../build/Release/world.node');
world.update();
Run Code Online (Sandbox Code Playgroud)

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 = []
Run Code Online (Sandbox Code Playgroud)

在Linux shell上,有些设置:

node-waf configure
Run Code Online (Sandbox Code Playgroud)

要构建,运行:

node-waf
Run Code Online (Sandbox Code Playgroud)

去测试:

node demo/demo.js
Run Code Online (Sandbox Code Playgroud)

输出:

Updating World
Run Code Online (Sandbox Code Playgroud)