首页 > 编程 > C++ > 正文

c++编写node的addon(4) --callback

2019-11-08 19:41:43
字体:
来源:转载
供稿:网友

1.环境

Ubuntu 14.04

node 4.5.0

node-gyp 3.4.0

2.项目

新建项目,加入组件nan和bindings

方法一、在项目文件的node_modules中复制组件nan和bindings的全部代码包;

方法二、在package.json的dependencies中加入这两个组件,用nmp安装

3.c++源码

//addon.cc#include <nan.h>void RunCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) {	v8::Local<v8::Function> cb = info[0].As<v8::Function>();	const unsigned argc = 1;	v8::Local<v8::Value> argv[argc] = {Nan::New("hello world").ToLocalChecked()};	Nan::MakeCallback(Nan::GetCurrentContext()->Global(), cb, argc, argv);}void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {	Nan::SetMethod(module, "exports", RunCallback);}NODE_MODULE(addon, Init)4.binding.gyp

{	"targets": [		{			"target_name":"addon",			"sources":["addon.cc"],			"include_dirs":[				"<!(node -e /"require('nan')/")"			]		}	]}5.js源码

var addon = require('bindings')('addon');addon(function(msg){	console.log(msg[0]);	console.log(msg[1]);});6.编译addon

cd到源码目录下

node-gyp configure build   7.执行

cd 到源码目录下

node hello.js
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选