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

c++编写node的addon(9) --pass wrapped

2019-11-08 18:36:32
字体:
来源:转载
供稿:网友

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++源码

//myobject.h #ifndef MYOBJECT_H#define MYOBJECT_H#include <nan.h>class MyObject : public Nan::ObjectWrap {	public:		static void Init();		static v8::Local<v8::Object> NewInstance(v8::Local<v8::Value> arg);		double Val() const {return val_;}					PRivate:		MyObject();		~MyObject();				static Nan::Persistent<v8::Function> constructor;		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);		double val_;		};#endif
//myobject.cc#include <node.h>#include "myobject.h"MyObject::MyObject(){};MyObject::~MyObject(){};Nan::Persistent<v8::Function> MyObject::constructor;void MyObject::Init(){	Nan::HandleScope scope;		//Prepare constructor template 	v8::Local<v8::FunctionTemplate> tp1 = Nan::New<v8::FunctionTemplate>(New);	tp1->SetClassName(Nan::New("MyObject").ToLocalChecked());	tp1->InstanceTemplate()->SetInternalFieldCount(1);		constructor.Reset(tp1->GetFunction());}void MyObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {	MyObject* obj = new MyObject();	obj->val_ = info[0]->IsUndefined()?0:info[0]->NumberValue();	obj->Wrap(info.This());		info.GetReturnValue().Set(info.This());}v8::Local<v8::Object> MyObject::NewInstance(v8::Local<v8::Value> arg) {	Nan::EscapableHandleScope scope;		const unsigned argc = 1;	v8::Local<v8::Value> argv[argc] = {arg};	v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);	v8::Local<v8::Object> instance = cons->NewInstance(argc, argv);		return scope.Escape(instance);}
//addon.cc#include <nan.h>#include "myobject.h"using namespace v8;void CreateObject(const Nan::FunctionCallbackInfo<v8::Value>& info) {	info.GetReturnValue().Set(MyObject::NewInstance(info[0]));}void Add(const Nan::FunctionCallbackInfo<v8::Value>& info) {	MyObject* obj1 = Nan::ObjectWrap::Unwrap<MyObject>(info[0]->ToObject());	MyObject* obj2 = Nan::ObjectWrap::Unwrap<MyObject>(info[1]->ToObject());		double sum = obj1->Val() + obj2->Val();		info.GetReturnValue().Set(Nan::New(sum));}void InitAll(v8::Local<v8::Object> exports) {	MyObject::Init();		exports->Set(Nan::New("createObject").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(CreateObject)->GetFunction());	exports->Set(Nan::New("Add").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Add)->GetFunction());}NODE_MODULE(addon, InitAll)4.binding.gyp

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

//addon.jsvar addon = require('bindings')('addon');var obj1 = addon.createObject(10);var obj2 = addon.createObject(20);var result = addon.Add(obj1, obj2);console.log(result);6.编译addon

cd到源码目录下

node-gyp configure build7.执行

cd 到源码目录下

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

图片精选