go runtime_error ai_generated true

恐慌:运行时错误:cgo回调包含未固定的Go指针

panic: runtime error: cgo callback has unpinned Go pointer

ID: go/cgo-callback-gc-pin

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
1.22 active
1.23 active

根因分析

将Go指针传递给C函数,该函数存储了指针并在之后回调,但Go内存未固定,导致GC移动了它。

English

Passing a Go pointer to a C function that stores it and later calls back, but the Go memory was not pinned, causing GC to move it.

generic

解决方案

  1. 90% 成功率 Use `runtime.Pin` to pin the Go object before passing to C
    p := &myStruct{}
    runtime.Pin(p)
    defer runtime.Unpin(p)
    C.callback(unsafe.Pointer(p))
  2. 85% 成功率 Allocate C memory and copy data
    cMem := C.malloc(C.size_t(unsafe.Sizeof(myStruct{})))
    C.callback(cMem)
    C.free(cMem)

无效尝试

常见但无效的做法:

  1. Using `runtime.KeepAlive` after callback 70% 失败

    KeepAlive only prevents GC before the call, does not pin during C execution.

  2. Making the pointer a global variable 50% 失败

    GC can still move global pointers if not pinned.