参考
目的通过c++扩展新模块。
例子代码 wget
解压后在./node-v0.8.8/test/addons/hello-world
一、编写模块:
点击(此处)折叠或打开
-
#include <node.h>
-
#include <v8.h>
-
-
using namespace v8;
-
-
Handle<Value> Method(const Arguments& args) {
-
HandleScope scope;
-
return scope.Close(String::New("world"));
-
}
-
-
void init(Handle<Object> target) {
-
NODE_SET_METHOD(target, "hello", Method);
-
}
-
-
NODE_MODULE(binding, init);
二、编写 binding.gyp
三、编译过程
采用node-gyp组织项目。
1、安装 node-gyp
npm install -g node-gyp
2、编译过程
a、进入目录 cd ./node-v0.8.8/test/addons/hello-world (node-v0.8.8源码自带列子) b、node-gyp configure
c、node-gyp build (默认Debug)
注:node-gyp build -r(编译release)
四、使用库
-
var assert = require('assert');
-
var binding = require('./build/Release/binding');
-
assert.equal('world', binding.hello());
-
console.log('binding.hello() =', binding.hello());
-
~
五、配置文件 参考
{
'targets': [
{
'target_name': 'raffle',
'sources': [ 'raffle.cc','keyvalue.pb.cc' ],
'
include_dirs': ['/usr/local/include/google/protobuf/'],
'libraries':['-lprotobuf','-lpthread']
}
]
}
六、复杂些的列子
-
//protoc --cpp_out=. ./keyvalue.proto ;node-gyp clean configure ;vi ./build/raffle.target.mk -lprotobuf -lpthread ;node-gyp build -r
-
#include <node.h>
-
-
#include <node_buffer.h>
-
#include <v8.h>
-
-
-
using namespace node;
-
using namespace v8;
-
using namespace std;
-
-
std::string ObjectToString(Local<Value> value) {
-
String::Utf8Value utf8_value(value);
-
return string(*utf8_value);
-
}
-
-
-
-
Handle<Value> testF(const Arguments& args) {
-
HandleScope scope;
-
if(args.Length() < 6) {
-
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
-
return scope.Close(Undefined());
-
}
-
if ( !args[0]->IsArray() || !args[1]->IsArray()
-
|| !args[2]->IsNumber() ){
-
-
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
-
return scope.Close(Undefined());
-
}
-
-
vector<int> tiletypeV;
-
Local<Object> ArryTiletype = args[0]->ToObject();
-
int len = ArryTiletype->Get(v8::String::New("length"))->ToObject()->Uint32Value();
-
for(int i = 0; i < len; i++){
-
Local<Value> element = ArryTiletype->Get(i);
-
tiletypeV.push_back(element->Int32Value());
-
}
-
-
-
-
int num = args[2]->ToNumber()->Int32Value();
-
-
-
vector<int> playerhandsV;
-
playerhandsV.push_back(1)
-
playerhandsV.push_back(2);
-
-
Local<Object> ArrayPlayerhands = args[1]->ToObject();
-
len = playerhandsV.size();
-
for( int i = 0; i < len; i++ ){
-
ArrayPlayerhands->Set(i, v8::Integer::New(playerhandsV[i]));
-
}
-
-
-
return scope.Close(Undefined());
-
-
}
-
-
void init(Handle<Object> target) {
-
NODE_SET_METHOD(target, "test", testF);
-
}
-
-
NODE_MODULE(MJ2AI, init);
阅读(4391) | 评论(0) | 转发(0) |