如何使用v8原生插件将c ++数组传递给node.js

我实现了一个使用unsigned char(uint8_t)内存创build缓冲区的c ++插件模块,并将其传递给node.js.

—- c ++ addon.cpp —-

 void get_frame_buffer(const FunctionCallbackInfo<Value>& args){ Isolate* isolate = helper.get_current_isolate(); if (!args[0]->IsUint32()&& !args[1]->IsUint32()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong arguments"))); return; } int width = args[0]->Uint32Value(); int height = args[1]->Uint32Value(); uint8_t* buf = new uint8_t[width * height * 4]; int length = width * height; memset(buf, 0, sizeof(buf)); for (int i = 0; i < length; i++) { buf[i * 4 + 0] = 128; buf[i * 4 + 1] = 128; buf[i * 4 + 2] = 128; buf[i * 4 + 3] = 255; } Local<External> ext = External::New(isolate, buf); Local<Object> obj = ext->ToObject(); args.GetReturnValue().Set(obj); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "GetFrameBuffer", get_frame_buffer); } NODE_MODULE(glAddonNode, Init) 

—- Node.js中的received.js —-

 const module = require('./addon.js'); var Received = function() { this._module = new module.Module; } Received.prototype.get_frame_buffer = function(width, height) { var c++_buf = this._module.GetFrameBuffer(width, height); // c++_buf is received from c++ addon // but c++_buf is null console.log(c++_buf); } 

向node.js发送对象是成功的,我期望数组数据存在于接收的对象中,但该对象是空的。

怎么了?代码中有错吗? 如何使用v8::External对象将c ++数组传递给node.js? 或者,你知道另一种将c ++数组提供给node.js的方法吗?

另外,我想避免复制函数(memcpy(),node :: Buffer :: Copy()等)。

简短的回答是:你不能使用v8::External将C ++对象暴露给JavaScript。

External的预期用例是将C ++对象与JS暴露的对象相关联,将它们存储在只能从C ++访问的“内部字段”中。 例如,可以将uint8_t数组(包装在External )存储在某个对象的内部字段中,然后当该对象从JS传递给您的C ++callback之一时,从其内部字段获取External以检索原始的uint8_t数组。 但是直接将C ++数组作为对象属性暴露给JavaScript是没有任何魔力的。

为了在C ++和JavaScript之间快速共享二进制数据, node::Buffer s可能就是你想要的。 也许这个问题: 传递Node.js缓冲区到C ++插件是你在找什么? 这个问题: 节点缓冲区到字符数组提供了双向转换的代码。