我目前正在开发一款运行在服务器上,在浏览器中显示数据的模拟器。
为了提供文件服务、通讯等功能,我想使用Node.js。但是,我不确定它在计算方面是否能够表现出我所期望的性能,因此我想用C++来开发模拟部分。
这个模拟器被划分为几个不同的“世界”,每个世界都有一些初始参数。
最佳的方式是什么?
我目前正在开发一款运行在服务器上,在浏览器中显示数据的模拟器。
为了提供文件服务、通讯等功能,我想使用Node.js。但是,我不确定它在计算方面是否能够表现出我所期望的性能,因此我想用C++来开发模拟部分。
这个模拟器被划分为几个不同的“世界”,每个世界都有一些初始参数。
最佳的方式是什么?
V8允许从JavaScript调用C++代码。
因此,您的代码可以分为3个部分:
World
所在的地方。World
类的部分。首先,了解V8和C++之间的通信方式。Google提供了一个指南:https://developers.google.com/v8/embed
然后,您需要node.js特定的glue。请参见http://www.slideshare.net/nsm.nikhil/writing-native-bindings-to-nodejs-in-c和http://syskall.com/how-to-write-your-own-native-nodejs-extension
来自上面的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)
}
演示/演示.js
var world = require('../build/Release/world.node');
world.update();
是一个Microsoft Windows脚本宿主环境,允许使用VBScript和JScript编写脚本程序,并且可以与操作系统和其他应用程序进行交互。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