You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Deno中获取Buffer实例的内存引用地址?

Deno 中获取缓冲区指针的实现方案

可以实现,Deno 内置的 Deno.UnsafePointer.of() 方法可直接获取 TypedArray 底层数据的起始指针,等效于 Node 中 buf.address() 的效果。

代码示例

// 若使用deno std的Buffer实例,写法如下
import { Buffer } from "https://deno.land/std/io/buffer.ts";

// 构造缓冲区
const uint8Data = new Uint8Array(10).fill(41);
const buf = new Buffer(uint8Data);

// 获取指针,等效Node的buf.address()
const bufferPointer = Deno.UnsafePointer.of(buf.bytes());
// 如果直接使用Uint8Array,写法更简单:
// const bufferPointer = Deno.UnsafePointer.of(uint8Data);

// 打印指针的数值地址
console.log(Number(bufferPointer));

注意事项

  • 运行该功能需要开启对应权限和不稳定特性标识,启动命令为:deno run --allow-ffi --unstable-ffi 你的脚本文件名.ts
  • 获取到的指针可直接传入 Deno.dlopen 加载的外部函数作为参数使用,符合FFI接口规范
  • 重要提示:TypedArray被垃圾回收后对应指针会变为野指针,访问会导致进程崩溃,使用指针期间请手动持有TypedArray的引用,避免被GC提前回收
  • std的Buffer实例的bytes()方法返回的是其底层持有的Uint8Array视图,取该视图的指针就是缓冲区的起始地址

FFI 调用示例

如果需要把缓冲区传给外部动态库的函数,可参考以下写法:

// 加载外部动态库示例(以linux下的so文件为例)
const lib = Deno.dlopen("./libtest.so", {
  // 假设C侧函数定义为 void read_buf(char* buf, int length)
  read_buf: {
    parameters: ["pointer", "i32"],
    result: "void",
  }
});

const testBuf = new Uint8Array([0x41, 0x41, 0x41, 0x41]);
const ptr = Deno.UnsafePointer.of(testBuf);
// 调用外部函数
lib.symbols.read_buf(ptr, testBuf.length);

// 使用完成后关闭动态库
lib.close();

内容的提问来源于stack exchange,提问作者odium

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:45:03