2015-06-23 25 views
2

我正在使用NAN在node.js中包含一個C++庫。我知道如何在兩者之間來回傳遞數字和字符串,但我不明白如何傳遞數組。我想這樣做是這樣的:使用NAN將數組從node.js傳遞到C++ v8

index.js

var test = require('bindings')('test'); 

var buffer = [0,0,0,0,0,0.1,0,0,0,0,-0.1]; 
test.encode(buffer, buffer.length); 

test.cc

var encoder = new Encoder(); 

NAN_METHOD(Encode){ 

    //the next line is incorrect, I want to take the buffer array and pass it as a pointer to the encodeBuffer() function 
    Local<Number> buffer = args[0].As<Number>(); 

    //get the integer value of the second argument 
    Local<Number> buffer_length = args[1].As<Number>(); 
    int bl_int = buffer_length->IntegerValue(); 

    //call function 
    encoder.encodeBuffer(buffer, bl_int); 
} 

void Init(Handle<Object> exports) { 
    exports->Set(NanNew("encode"), NanNew<FunctionTemplate>(Encode)->GetFunction()); 
} 

實際的方法,我想從C++庫被宣佈使用:

void encodeBuffer(float *buffer, size_t l); 

我試着看文檔,但他們沒有說任何關於指針和數組..我是mi什麼東西?

+0

嘿@nevos做我的回答可以幫助您? –

+0

是的@JohnSmith,謝謝! – nevos

回答

5

比方說你有一個緩衝區,我怎麼正常地是這樣的:

var buffer = new Buffer([10, 20, 30, 40, 50]); 

然後將它傳遞到擴展:

Extension.to_image(buffer, buffer.length 

,在我的本地代碼:

NAN_METHOD(to_image) { 
    unsigned char*buf = (unsigned char*) node::Buffer::Data(args[0]->ToObject()); 
    unsigned int size = args[1]->Uint32Value(); 

正如你可以看到在末尾我有一個緩衝區和緩衝區長度轉移到我的C++代碼。

這裏是一個很好的文章:http://luismreis.github.io/node-bindings-guide/docs/arguments.html

而另一個很好的一個:http://www.puritys.me/docs-blog/article-286-How-to-pass-the-paramater-of-Node.js-or-io.js-into-native-C/C++-function..html

+0

這是否也適用於浮點陣列? – nevos

+0

嗨@nevos我​​沒有測試它,但我認爲是這樣! :) –