基本思想是返回指针,然后在每个视频帧上创建Vec
后使用指针显示图像:
JavaScript:
var ptr = exports.alloc(size);
let bytes = new Uint8ClampedArray(exports.memory.buffer, ptr, size);
let image = new ImageData(bytes, 320, 240);
function tick() {
requestAnimationFrame(tick);
ctx.drawImage(video, 0, 0, width, height);
let imageData = ctx.getImageData(0, 0, width, height).data;
bytes.set(imageData);
exports.create_vector();
ctx.putImageData(img, 0, 0);
}
铁锈:
#[no_mangle]
pub extern "C" fn alloc(capacity: usize) -> *mut c_void {
let mut buf = Vec::with_capacity(capacity);
let ptr = buf.as_mut_ptr();
mem::forget(buf);
return ptr as *mut c_void;
}
#[no_mangle]
pub extern "C" fn create_vector() {
let _: Vec<u8> = Vec::with_capacity(320 * 240);
}
以下是错误消息:
Chrome浏览器:
Uncaught TypeError: Cannot perform %TypedArray%.prototype.set on a detached ArrayBuffer
at Uint8ClampedArray.set (<anonymous>)
at tick
Safari:
This webpage was reloaded because a problem occurred
Mozilla:
DOMException: "An attempt was made to use an object that is not, or is no longer, usable"
TypeError: Underlying ArrayBuffer has been detached from the view
罪魁祸首似乎是:
let bytes = new Uint8ClampedArray(exports.memory.buffer, ptr, size);
// ...
exports.create_vector();
// ...
即,当我调用ptr
后再次尝试使用exports.create_vector
时,浏览器崩溃。
这是怎么回事?有解决办法吗?
答案 0 :(得分:4)
当您分配一个新缓冲区,而WASM“进程”没有为其分配足够的内存时,浏览器将分配一个更大的新缓冲区,并将所有数据从旧位置复制到其中。在WASM解释器中,它非常透明,但是传递给JavaScript的所有指针(用于构造Uint8ClampedArray
的指针)都会失效。据我所知,有两种解决方案: