4

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.

cbuchart
  • 10,847
  • 9
  • 53
  • 93
S. Vaughn
  • 86
  • 1
  • 7

1 Answers1

3

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.

ZachB
  • 13,051
  • 4
  • 61
  • 89
  • You're right in that Uint8Array would be preferred, but for this particular implementation, it was specified my program must return an ArrayBuffer. As for the rest, I did end up figuring it out, but the kInternalized was new to me. Thank you. – S. Vaughn Jun 12 '17 at 20:19
  • I trie to use ArrayBufferCreationMode::kInternalized. But an exception is raised. – user3395707 Mar 16 '21 at 08:58