嗯,V8 允许从 JavaScript 调用 C++ 代码。
所以你的代码可以分为 3 部分:
- 普通 C++,不知道 Node.js 和 V8。这将是哪里
World
is.
- 粘合node.js/V8-C++代码,允许JS“看到”你的部分内容
World
class.
- 普通 JavaScript 代码,通过“粘合”层与 C++ 端通信
首先,了解V8和C++如何通信。谷歌为此提供了一个指南:https://developers.google.com/v8/embed https://developers.google.com/v8/embed
然后,您需要 Node.js 特定的粘合剂。看http://www.slideshare.net/nsm.nikhil/writing-native-bindings-to-nodejs-in-c http://www.slideshare.net/nsm.nikhil/writing-native-bindings-to-nodejs-in-c and http://syskall.com/how-to-write-your-own-native-nodejs-extension http://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.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
To test:
node demo/demo.js
Output:
Updating World