我正在学习如何通过this tutorial使用Rust来瞄准WASM。我希望能够将我的域代码与将其暴露给WASM的代码分开。这样,我就可以在非WASM应用程序中重用域代码,而无需大惊小怪。我找不到任何这样做的例子,我也不知道它是否被支持。
现在,我正在做的是用另一个结构包装我的普通Rust结构,该结构对域类的公共方法进行了包装。我几乎可以肯定这不是正确的方法,但目前它是有效的。
我希望能够将CellValue绑定到WASM。
// Inside a vanilla Rust library
// We could bind CellValue with #[wasm_bindgen],
// but I want to keep all WASM stuff out of this library
enum CellValue {
Live = 0,
Dead = 1
}
// ...
struct World {
// ...
cells: Vec<CellValue> // need to bind a direct reference to the values in here
}这就是我向WASM公开World的方式--我将它包装在GOL中,并在GOL中实现方法,以便WASM可以与World交互。
// Inside the wasm binding library
#[wasm_bindgen]
pub struct GOL {
world: gol::World
}
#[wasm_bindgen]
impl GOL {
pub fn make_new(rows: usize, cols: usize) -> Self
{
Self {
world: GameOfLife::make_new(rows, cols)
}
}
// and so on...
}对于CellValue,我不能模仿我对GOL采取的方法,因为我需要能够引用World保存的每个单元格中的数据。
就像我说的,我跳过这些圈套的全部原因是为了避免我的域名代码中充斥着#[wasm_bindgen]。有没有可能得到这种绑定呢?
发布于 2019-06-21 14:21:55
更新:我通过查看this库找到了一个可行的解决方案。这是一个以这种方式编写的ZX频谱仿真器,将wasm_bindgen隔离在一个接口中。其范例是通过不安全的指针进行互操作,如下所示:
#[wasm_bindgen]
pub fn get_cell_value(world: *mut World) -> *const CellValue // return a raw reference to the type defined in the domain
{
// Return a reference to the first element in the array
}然后,在JavaScript端,执行如下操作:
import { memory } from "gol/gol_bg"; // Actual WASM generated by wasm_bindgen
import { make_world, get_cell_array } from "wasm-game-of-life";
// ...
const world = make_world(width, height);
const cellsPtr = get_cells_array(world); // Pointer to the first element of the Vec
const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);https://stackoverflow.com/questions/56676637
复制相似问题