ffi.toBuffer(pointer, length[, copy])


从本地内存创建一个 Buffer

🌐 Creates a Buffer from native memory.

copytrue 时,返回的 Buffer 拥有其自己的复制内存。 当 copyfalse 时,返回的 Buffer 直接引用原始本地内存。

🌐 When copy is true, the returned Buffer owns its own copied memory. When copy is false, the returned Buffer references the original native memory directly.

使用 copy: false 是一种零拷贝的应急方法。返回的 Buffer 是一个可写的外部内存视图,因此在 JavaScript 中的写入会直接更新原始本地内存。调用者必须保证:

🌐 Using copy: false is a zero-copy escape hatch. The returned Buffer is a writable view onto foreign memory, so writes in JavaScript update the original native memory directly. The caller must guarantee that:

  • pointer 在返回的 Buffer 的整个生命周期内保持有效。
  • length 保持在分配的本地区域内。
  • 在 JavaScript 仍然使用 Buffer 的情况下,没有本地代码会释放或重新利用那块内存。
  • 内存保护被遵守。例如,只读内存页不得被写入。

如果这些保证未被满足,读取或写入 Buffer 可能会破坏内存或导致进程崩溃。

🌐 If these guarantees are not met, reading or writing the Buffer can corrupt memory or crash the process.