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

5.2k views Asked by At

I am using NAN for including a c++ library in node.js. I understand how to pass numbers and strings back and forth between the two, but I don't understand how to pass arrays. What I would like to do is something like this:

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

The actual method I would like to use from c++ library is declared:

void encodeBuffer(float *buffer, size_t l);

I tried looking at the documentation but they don't say anything about pointers and arrays.. Am I missing something?

1

There are 1 answers

2
John Smith On BEST ANSWER

Lets say you have a Buffer, how I normally pass is like this:

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

Then to Pass it to the extension:

Extension.to_image(buffer, buffer.length

And In my native code:

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

As you can see at the end I have a buffer and the buffer length transferred to my c++ code.

Here is a good article: http://luismreis.github.io/node-bindings-guide/docs/arguments.html

And another very good one: 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