问题
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.
回答1:
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.
回答2:
http://v8.paulfryzel.com/docs/master/classv8_1_1_array_buffer.html#a28e84424cddbe397f3ee3d920189bc04
Local< ArrayBuffer > v8::ArrayBuffer::New ( Isolate * isolate, size_t byte_length)
Create a new ArrayBuffer. Allocate |byte_length| bytes. Allocated memory will be owned by a created ArrayBuffer and will be deallocated when it is garbage-collected, unless the object is externalized.
来源:https://stackoverflow.com/questions/39796251/copy-data-into-v8arraybuffer