在我的 AssemblyScript 模块和我的 JS 之间共享内存的正确方法是什么?

What's the correct way to share memory between my AssemblyScript module and my JS?

我正在关注这段代码 here,试图在我的 AssemblyScript 代码和我的 JS 之间共享内存:

  let aryPtr = instance.exports.allocateF32Array(3);
  let ary = new Float32Array(instance.exports.memory.buffer, aryPtr, 3);

  ary[0] = 1.0;
  ary[1] = 2.0;
  instance.exports.addArray(aryPtr);

还有我的index.ts:

export function allocateF32Array(length: i32): Float32Array {
  return new Float32Array(length);
}

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}

但这会导致 addArray 中的 RuntimeError: memory access out of bounds。我是不是误解了它的工作原理?

我建议将 the official loader 用于此类目的。

在JavaScript方面:(例如node.js)

const fs = require("fs");
const loader = require("@assemblyscript/loader");
const module = loader.instantiateSync(
  fs.readFileSync("optimized.wasm"),
  {}
);
var ptrArr = module.__retain(module.__allocArray(module.FLOAT32ARRAY, [1, 2, 0]));
console.log('length:', module.addArray(ptrArr));

const arr = module.__getFloat32Array(ptrArr);
console.log('result:', arr[2]);

// free array
module.__release(ptrArr);

在 AssemblyScript 方面:

export const FLOAT32ARRAY = idof<Float32Array>();

export function addArray(data: Float32Array): i32 {
  data[2] = data[0] + data[1];
  return data.length;
}