c语言node程序,如何从Node.js调用C代码?
那么V8允許從
JavaScript調用C代碼.
所以你可以有3部分代碼:
>正常C,不知道node.js和V8.這將是世界的地方.
> Glue node.js / V8-C代碼,允許JS“查看”你的世界類的部分.
>正常的JavaScript代碼,它通過“膠”層與C端進行通信
從上面的幻燈片鏈接:
#include
#include
using namespace v8;
extern "C" {
static void init(Handle 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
using std::cout;
using std::endl;
World MyWorld;
void World::update() {
cout << "Updating World" << endl;
}
SRC / bind.cpp
#include
#include
#include "world.h"
using namespace v8;
static Handle UpdateBinding(const Arguments& args) {
HandleScope scope;
MyWorld.update();
return Undefined();
}
static Persistent updateFunction;
extern "C" {
static void init(Handle obj) {
v8::HandleScope scope;
Local updateTemplate = FunctionTemplate::New(UpdateBinding);
updateFunction = v8::Persistent::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
去測試:
node demo/demo.js
輸出:
Updating World
總結
以上是生活随笔為你收集整理的c语言node程序,如何从Node.js调用C代码?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言键盘连续双击程序,编了个C语言的键
- 下一篇: c语言调用函数计算分段函数值,输入x,计