6

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?

0

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @nevos I didn't test it but I thinks so! :)
is it possible to pass to get length directly from args[0] ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.