In short, I have an addon that completes an operation which results in a uint8_t
array. I need to convert this array and its contents to an ArrayBuffer
, and return that.
Conversely, the addon can also accept an ArrayBuffer
as input, and I need to convert that, along with its contents, into a uint8_t
array.
I am having trouble finding clear documentation on how to do so. I am new to Node, v8, addons, etc. If someone knows how to do this and could help me out that would be great.
You might want to be working with a Uint8Array
instead of an ArrayBuffer
, but ...
To make an ArrayBuffer
from an existing block of memory:
// given void* data
v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(
Isolate::GetCurrent(), data, byte_length, ArrayBufferCreationMode::kInternalized)
Docs are here. The final argument controls if the memory block will be free
'd by v8 when the ArrayBuffer is GC'ed. If you use kInternalized
, the memory must be freeable with free
.
To get the memory backing an ArrayBuffer
, use ab->GetContents()
. That returns a Contents class instance, which has a void* Data()
method.
See https://stackoverflow.com/a/31712512/1218408 for some additional examples.