我有一个本地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
  • 关于c++ - Node 缓冲区到char数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28171481/

    10-10 11:02