# 错误：cgo：C函数返回错误：errno 2

- **ID:** `go/cgo-errno-handling`
- **领域:** go
- **类别:** system_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

C函数在失败时设置`errno`，但Go代码未检查，导致静默失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.18 | active | — | — |
| 1.19 | active | — | — |

## 解决方案

1. **Check return value and use `C.CString` to get error message** (90% 成功率)
   ```
   ret := C.someCFunction()
if ret != 0 {
    errno := C.errno
    errStr := C.GoString(C.strerror(errno))
    return fmt.Errorf("C error: %s", errStr)
}
   ```
2. **Use `cgo.Handle` to capture error in a thread-safe way** (80% 成功率)
   ```
   // Not directly applicable; use mutex to protect errno reading
   ```

## 无效尝试

- **Ignoring the return value of C function** — No error handling at all. (90% 失败率)
- **Using `C.errno` directly without thread safety** — errno is thread-local in C, but Go may not preserve it. (60% 失败率)
