使用NAN将数组从node.js传递到c ++ v8

时间:2015-06-23 09:19:32

标签: javascript c++ node.js node-gyp node.js-addon

我使用NAN在node.js中包含c ++库。我理解如何在两者之间来回传递数字和字符串,但我不明白如何传递数组。我想做的是这样的事情:

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

我试着查看文档,但他们没有说明指针和数组。我错过了什么吗?

1 个答案:

答案 0 :(得分: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