通过WASM构建新的Rust Vec时,JavaScript ArrayBuffer“分离”

时间:2018-08-02 17:33:23

标签: javascript rust webassembly

基本思想是返回指针,然后在每个视频帧上创建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);
}

Here is the actual code

以下是错误消息:

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时,浏览器崩溃。

这是怎么回事?有解决办法吗?

1 个答案:

答案 0 :(得分:4)

当您分配一个新缓冲区,而WASM“进程”没有为其分配足够的内存时,浏览器将分配一个更大的新缓冲区,并将所有数据从旧位置复制到其中。在WASM解释器中,它非常透明,但是传递给JavaScript的所有指针(用于构造Uint8ClampedArray的指针)都会失效。据我所知,有两种解决方案:

  • 在初始化时在WASM“进程”中分配足够的内存,并立即对其进行分配,这样只要内存使用率低于选定的大小,指针就不会失效。
  • 跟踪传递给JavaScript的缓冲区以及此类错误的“更新”指针。