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

如何在Go中调用带void**参数的C函数?

在Go中调用带void**参数的C函数的正确方式

错误原因

你之前的写法触发了如下类型错误:

cannot use _cgo0 (variable of type unsafe.Pointer) as type *unsafe.Pointer in argument to _Cfunc_create_key_pair

问题出在使用uintptr类型变量作为指针载体——uintptr是整数类型而非指针类型,C函数要求的void**是指向指针的指针,传递uintptr变量的地址无法匹配参数类型,导致类型不兼容。

正确调用方式

需要用unsafe.Pointer对应C的void*类型,对于void**参数,我们要传递一个指向unsafe.Pointer变量的指针,再通过unsafe.Pointer()转换为C能识别的类型:

/*
static int create_key_pair(void** key) {
    // 示例实现:为key分配内存并赋值
    *key = malloc(16);
    return 0;
}
*/
import "C"
import "unsafe"

func CreateKey() {
    var key unsafe.Pointer
    // 将&key转换为unsafe.Pointer,对应C的void**类型
    C.create_key_pair(unsafe.Pointer(&key))
    
    // 后续操作示例:
    // 若key指向C结构体,可转换为对应指针类型:(*C.struct_key)(key)
    // 若C函数分配了内存,记得手动释放避免泄漏:defer C.free(key)
}

补充说明

  • unsafe.Pointer是Go与C交互的指针转换桥梁,可安全在Go指针和C指针之间转换。
  • 如果C函数为key分配了堆内存,必须在Go侧调用C.free()手动释放,建议配合defer确保执行。
  • 若key指向特定C数据结构,可将unsafe.Pointer直接转换为对应结构体指针,例如(*C.struct_my_key)(key)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:18