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

- **ID:** `go/cgo-callback-gc-pin`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.22 | active | — | — |
| 1.23 | active | — | — |

## 解决方案

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

## 无效尝试

- **Using `runtime.KeepAlive` after callback** — KeepAlive only prevents GC before the call, does not pin during C execution. (70% 失败率)
- **Making the pointer a global variable** — GC can still move global pointers if not pinned. (50% 失败率)
