Copy data into v8::ArrayBuffer

爷,独闯天下 提交于 2020-05-26 05:56:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!