[英]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.我正在使用节点 6.9.1,我尝试创建一个 cpp 插件来创建节点缓冲区对象。 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:这段代码编译得很好,但是当我访问通过回调获得的缓冲区的 .length 属性时会导致错误:
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.我找到了几个教程,但它们都使用早期版本的 v8/node api,我找不到任何信息在最近的 Node 版本中创建缓冲区的正确方法是什么。 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 的
NewBuffer
助手:
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. Node 的
node_buffer.h
也有一个公共构造函数,但它不一定跨版本一致。
I'm not positive, but your error might be because you've freed the raw data used to construct the buffer?我不是很肯定,但您的错误可能是因为您释放了用于构建缓冲区的原始数据?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.