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

Passing an array from node.js to c++ v8 using NAN

我正在使用 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);

我试着查看文档,但他们没有提到任何关于指针和数组的内容。我是不是漏掉了什么?

假设你有一个缓冲区,我通常是这样传递的:

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