Node Buffer to char array

泄露秘密 提交于 2019-12-20 03:52:44

问题


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

回答1:


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:

  • 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


来源:https://stackoverflow.com/questions/28171481/node-buffer-to-char-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!