1

I have a native NodeJS addon that accepts a Buffer instance as one of it's arguments.

I'm able to convert a char array into a Buffer with the following code, but looking for the other way around.

static v8::Local<v8::Object> create_buffer(char *data, unsigned long length) {
  node::Buffer *slow_buffer = node::Buffer::New(length);
  memcpy(node::Buffer::Data(slow_buffer), data, length);

  v8::Handle<v8::Value> constructor_arguments[3] = {
    slow_buffer->handle_,
    v8::Integer::New(length),
    v8::Integer::New(0)
  };

  v8::Local<v8::Object> global_object = v8::Context::GetCurrent()->Global();
  v8::Local<v8::Function> buffer_constructor = v8::Local<v8::Function>::Cast(global_object->Get(v8::String::New("Buffer")));

  return buffer_constructor->NewInstance(3, constructor_arguments);
}
ZachB
  • 13,051
  • 4
  • 61
  • 89
jviotti
  • 17,881
  • 26
  • 89
  • 148

1 Answers1

7

Maybe I'm late, but the following code should work:

#include <node.h>
#include <node_buffer.h>

void Test(const FunctionCallbackInfo<Value>& args)
{
  Local<Object> bufferObj = args[0]->ToObject();
  char* bufferData = node::Buffer::Data(bufferObj);
  size_t bufferLength = node::Buffer::Length(bufferObj);
}

Reference:

Daniele
  • 842
  • 8
  • 11
  • Getting a: `/usr/bin/node[3316]: ../src/node_buffer.cc:221:size_t node::Buffer::Length(v8::Local): Assertion obj->IsUint8Array() failed. 1: node::Abort() [node]` with this. – Ates Goral Aug 11 '17 at 19:30
  • I wonder if the transferred string from buffer to char* is well ended. – 4t8dds Nov 09 '17 at 10:53