Search code examples
javascriptc++qtv8arraybuffer

Copy data into v8::ArrayBuffer


I'm writing a Javascript interpreter in C++ using v8. I need to pass a char buffer into an ArrayBuffer so that it gets garbage collected. Here is my code:

QByteArray data_buffer(file.readAll().data(), file.size());

v8::Handle<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(args.GetIsolate(), data_buffer.size());
//insert code to copy data from data_buffer to ab
args.GetReturnValue().Set(ab);

If I use the constructor from the documentation in which I pass a pointer to the data, I'll have to deal with the memory myself and I don't want that.

I want to avoid allocating memory and let v8 do it's own memory management. Couldn't find a way using Set() or any other function.

Any suggestions on how to copy data to the arraybuffer? Or how can I use the 2 parameters constructor to let v8 deal with the memory my data uses?

Documentation here: http://bespin.cz/~ondras/html/classv8_1_1ArrayBuffer.html Thanks.


Solution

  • Found a way:

    memcpy(ab->GetContents().Data(), data_buffer.data(), data_buffer.size());
    

    Now I don't need to allocate memory and everything is garbage collected.