简体   繁体   中英

How do I properly create a Buffer object from a node native addon?

I am using node 6.9.1 and I try to create a cpp addon that will create Node Buffer objects. After some research I came up with the following code:

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

using v8::Local;
using v8::Object;
using v8::HandleScope;
using v8::Isolate;

Local<Object> create_buffer(Isolate* isolate, char* rawData, int length) {
  HandleScope scope(isolate);
  Local<Object> buf = node::Buffer::New(
    isolate,
    rawData,
    length).ToLocalChecked();
  return buf;
}

which I use as follows:

Local<Value> buff = create_buffer(isolate, rawData, length);
const unsigned argc = 1;
Local<Value> argv[argc] = { buff };
cb->Call(Null(isolate), argc, argv);

This code compiles just fine but causes an error when I access the .length property of the buffer I get through the callback:

Security context: 0x9d84c7cfb51 <JS Object>#0#

I found several tutorials but all of them use an earlier version of v8/node api and I cannot find any info what is a proper way to create buffer in the recent Node versions. Also it is possible that I have made a mistake somewhere. Thanks in advance if you can guide me in the right direction.

The best way is to use NAN's NewBuffer helper:

Nan::MaybeLocal<v8::Object> mybuffer = Nan::NewBuffer(size);
Nan::MaybeLocal<v8::Object> mybuffer = Nan::NewBuffer(mydata, size);

Node's node_buffer.h also has a public constructor, but it's not necessarily consistent across versions.

I'm not positive, but your error might be because you've freed the raw data used to construct the buffer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM