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

如何在Deno中实现TS buffer到C char**的双指针赋值?

如何将TypeScript的Buffer赋值给C语言的char**参数?

问题场景

我尝试将Deno/TypeScript中创建的Buffer内容传递给C语言的char**参数,但未能成功,具体流程:

  • C调用以char**为参数的Deno回调函数
  • Deno创建Buffer并写入字符串内容
  • Deno尝试将Buffer地址赋值给char**
  • C读取Deno返回的字符串

环境信息

deno 1.31.1 (release, x86_64-pc-windows-msvc)
v8 11.0.226.13
typescript 4.9.4

C代码

void test() {
    char* Buffer;
    call_deno_function((char**)&Buffer);
    printf("The Deno response is %s", Buffer); // 预期输出"Hello",实际输出"null"
}

Deno TypeScript代码

export function bind(win, element, func) : number {
    const callbackResource = new Deno.UnsafeCallback(
        {
            parameters: [
                   'pointer' // <------ 对应char**
                   ],
            result: 'void',
        } as const,
        (
            param_response: Deno.Pointer,
        ) => {
            console.log("This is Deno callback function...");
            const result = String("Hello");

            // `result`         : 回调结果字符串
            // `param_response` : 未初始化的(null)`char**`

            // 需要创建不会被垃圾回收的buffer,写入`result`后赋值给`param_response`

            // 创建Buffer
            const encoder = new TextEncoder(); // 创建TextEncoder实例
            const resultBytes = encoder.encode(result); // 将字符串转为字节
            const buf = new Uint8Array(resultBytes.length + 1); // 分配存储字符串的buffer
            buf.set(resultBytes); // 将字符串字节复制到buffer
            buf[resultBytes.length] = 0; // 设置空终止符

            // 将buffer `buf`赋值给`char**`
            param_response = buf; // <---------- 此处未生效
        },
    );
    // 省略绑定相关的后续代码
}

当前输出

This is Deno callback function...
The Deno response is null

预期输出

This is Deno callback function...
The Deno response is Hello

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:35:05