5

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

测试.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);

我尝试查看文档,但他们没有说任何关于指针和数组的内容。我错过了什么吗?

4

1 回答 1

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

于 2015-06-23T22:07:58.703 回答