我应该如何在 Wasm 内存中存储连续的 f64 值?

How should I store consecutive f64 values in Wasm memory?

我在写一个tiny compiler,直接输出Wasm。在我的源语言中,所有值都是 f64s,它们可以按索引写入(和读出)固定大小的缓冲区。

我正在尝试使用(?)Wasm 内存来存储该缓冲区。

当在内存中存储连续的 f64 值时,我应该在运行时通过将索引乘以 f64 的字节大小来导出地址,还是我可以以某种方式使用 align/offset?

实现此目的

在我最初的方法中(回想起来这很愚蠢)假设我可以只使用连续的索引并且不知何故我使用 f64.storef64.load 的事实会 "just work"。

它看起来像这样 .wat 文件:

(module
      (memory 1)
      (func (result f64)
          ;; Write 0 to index 99
          i32.const 99
          f64.const 0
          f64.store

          ;; Write 1 to index 100
          i32.const 100
          f64.const 1
          f64.store

          ;; Read from 99
          i32.const 99
          f64.load
      )
      (export "run" (func 0))
  )

我希望它输出 0 但它输出 -3.105036184601418e+231 我认为这是因为我在索引 99 处开始读取时正在读取的一些字节是在我写入时写入的索引 100。

上述 .wat 文件的 "correct" 版本是什么——一个将两个连续的 f64 值存储到内存中然后读取一个的文件——长什么样子?

可以找到官方 f64.load/f64.store 规范 here

When storing consecutive f64 values in memory, should I be deriving the address at runtime by multiplying the index by the byte size of an f64, or can I somehow achieve this using align/offset?

不,您无法通过 align/offset 获得此信息。

您必须将所有索引乘以 8(因为 f64 是 64 位/8 位 = 8)。

您可以在每次内存访问时直接这样做,或者另一种方法是定义两个实用函数:

  • (结果 f64)myload(索引 i32)和
  • () mystore(i32 索引, f64 值)

然后这些函数将在索引*8处执行load/store。