nevos nevos - 1 year ago 187
C++ Question

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

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:


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

var encoder = new Encoder();


//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?

Answer Source

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:

And another very good one:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download