0

I am writing a Node Addon Function That returns a Promise, I have code like this.

size_t outbufsize = 1000;
context->data.size = outbufsize;
context->data.data = new char[outbufsize];

When I finish work.

context->deffered.Resolve(Napi::ArrayBuffer::New(env, context->data.data, context->data.size));

Do I need to delete pointer "context->data.data"? if I delete this pointer. I get an undefine behavior ArrayBuffer on the Javascript side. But if I don't delete the pointer, I don't know if the memory is freed or not?

wdw
  • 11
  • 3
  • An ArrayBuffer is underlying binary data. It is still owned by you when you pass it to Node.js and the JavaScript side reflects that. So in terms of ownership you would need to keep it alive (or use a typed array and not an ArrayBuffer and copy it) – Benjamin Gruenbaum Apr 06 '22 at 14:19
  • I saw this in the document of NAN:"Note that when creating a Buffer using Nan::NewBuffer() and an existing char*, it is assumed that the ownership of the pointer is being transferred to the new Buffer for management. When a node::Buffer instance is garbage collected and a FreeCallback has not been specified, data will be disposed of via a call to free(). You must not free the memory space manually once you have created a Buffer in this way." – wdw Apr 07 '22 at 02:52

1 Answers1

0

I think I should return the Buffer instead of ArrayBuffer.

 context->deffered.Resolve(
         Napi::Buffer<char>::New(
         env,
         context->data.data,
         context->data.size,
         [](Napi::Env env, void *data)
         {
           free(data);
         }));

as the document say---that accept Napi::Finalizer, which is a function that will be invoked when the Napi::Buffer object has been destroyed.

wdw
  • 11
  • 3