v8插件編譯使用

目的:經過c++擴展新模塊。node


例子代碼  wget http://nodejs.org/dist/v0.8.8/node-v0.8.8.tar.gzc++


          解壓後在./node-v0.8.8/test/addons/hello-worldnpm


1、編寫模塊:ui


#include <node.h>google


#include <v8.h>spa


using namespace v8;element


Handle<Value> Method(const Arguments& args) {v8


  HandleScope scope;get


  return scope.Close(String::New("world"));源碼


}


void init(Handle<Object> target) {


  NODE_SET_METHOD(target, "hello", Method);


}


NODE_MODULE(binding, init);


2、編寫 binding.gyp


3、編譯過程


採用node-gyp組織項目。


一、安裝 node-gyp


npm install -g node-gyp


二、編譯過程


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)


4、使用庫


var assert = require('assert');


var binding = require('./build/Release/binding');


assert.equal('world', binding.hello());


console.log('binding.hello() =', binding.hello());


~


5、配置文件 參考


{


  'targets': [


    {


      'target_name': 'raffle',


      'sources': [ 'raffle.cc','keyvalue.pb.cc' ],


      'include_dirs': ['/usr/local/include/google/protobuf/'],


      'libraries':['-lprotobuf','-lpthread']


    }


  ]


}


6、複雜些的列子


//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);

相關文章
相關標籤/搜索