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);
private:
MyObject();
~MyObject();
static Nan::Persistent<v8::Function> constructor;
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void PlusOne(const Nan::FunctionCallbackInfo<v8::Value>& info);
double counter_;
};
#endif
//myobject.cc
#include <nan.h>
#include "myobject.h"
using namespace v8;
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);
//Prototype
tp1->PrototypeTemplate()->Set(Nan::New("plusOne").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(PlusOne)->GetFunction());
constructor.Reset(tp1->GetFunction());
}
void MyObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {
MyObject* obj = new MyObject();
obj->counter_ = 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);
}
void MyObject::PlusOne(const Nan::FunctionCallbackInfo<v8::Value>& info) {
MyObject* obj = ObjectWrap::Unwrap<MyObject>(info.This());
obj->counter_ += 1;
info.GetReturnValue().Set(Nan::New(obj->counter_));
}
//addon.cc
#include <nan.h>
#include "myobject.h"
void CreateObject(const Nan::FunctionCallbackInfo<v8::Value>& info) {
info.GetReturnValue().Set(MyObject::NewInstance(info[0]));
}
void InitAll(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Nan::HandleScope scope;
MyObject::Init();
module->Set(Nan::New("exports").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(CreateObject)->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.js
var addon = require('bindings')('addon');
var obj = addon(10);
console.log(obj.plusOne());
console.log(obj.plusOne());
console.log(obj.plusOne());
var obj2 = addon(20);
console.log(obj2.plusOne());
console.log(obj2.plusOne());
console.log(obj2.plusOne());
6. 编译addon
cd到源码目录下
node-gyp configure build
7.执行
cd 到源码目录下
node hello.js