节点缓冲区到字符数组

Node Buffer to char array

本文关键字:数组 字符 缓冲区 节点      更新时间:2023-10-16

我有一个原生的 NodeJS 插件,它接受一个Buffer实例作为它的参数之一。

我能够使用以下代码将char数组转换为Buffer,但正在寻找相反的方法。

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

也许我迟到了,但以下代码应该可以工作:

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

参考:

  • 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
  • https://github.com/nodejs/nan/blob/master/nan.h#L25