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

标签 c++ node.js performance v8 ffi

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

为了提供文件、通信和类似的东西,我想使用 Node.js。但是,我不确定它是否会像我希望的那样在计算部门表现得那么好,所以我想用 C++ 开发模拟部分。

模拟被分成不同的“世界”,它们都以一些初始参数开始。

最好的方法是什么?

最佳答案

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

所以你可以有 3 个部分的代码:

  • 普通 C++,不知道 node.js 和 V8。这将是 World 所在的位置。
  • 粘贴 node.js/V8-C++ 代码,让 JS 能够“看到”你的 World 类的部分内容。
  • 普通的 JavaScript 代码,通过“胶水”层与 C++ 端通信

首先,了解 V8 和 C++ 是如何通信的。谷歌为此提供了指南: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

来自上面的幻灯片链接:

#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/demo.js

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

脚本

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

关于c++ - 如何从 Node.js 调用 C++ 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12447479/

相关文章:

javascript - 如何让 learnyounode #9 杂耍异步工作

javascript - 如何将 Child_process.spawn 的 "Promise"语法转换为 "async/await"语法

javascript - 如何将 TypedArray 复制到另一个 TypedArray?

c# - 将持久化的 ADO 2.8 COM 记录集转换为 ADO.Net 数据集

c++ - 将循环转换为数学方程

c++ - 错误: function definition is marked dllimport

c++ - 用于重新排序无符号整数的 Constexpr 变量模板

c++ - 使用运算符重载添加存储在 vector 中的类对象

javascript - 如何使用 node.js 和 sequelize 更新对象中的值

c++ - 我可以告诉我的类是从哪个模板实例类继承的吗?