如何从Node.js调用C ++代码?
我目前正在开发一个在服务器上运行的模拟器,并且应该在浏览器中显示数据。
为了提供文件,通信和类似的东西,我想使用Node.js. 但是,我不确定它是否能像计算部门那样执行,所以我想用C ++来开发模拟部分。
仿真分为独立的“世界”,这些世界都以一些初始参数开始。
做这个的最好方式是什么?
那么,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-c和http://syskall.com/how-to-write-your-own-native-nodejs -延期
从上面的slideshare链接:
#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
build立,运行:
node-waf
去testing:
node demo/demo.js
输出:
Updating World