go
system_error
ai_generated
true
error: cgo: C function returned error: errno 2
ID: go/cgo-errno-handling
80%Fix Rate
85%Confidence
0Evidence
2025-01-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
Root Cause
C function sets `errno` on failure, but Go code does not check it, leading to silent failures.
generic中文
C函数在失败时设置`errno`,但Go代码未检查,导致静默失败。
Workarounds
-
90% success Check return value and use `C.CString` to get error message
ret := C.someCFunction() if ret != 0 { errno := C.errno errStr := C.GoString(C.strerror(errno)) return fmt.Errorf("C error: %s", errStr) } -
80% success Use `cgo.Handle` to capture error in a thread-safe way
// Not directly applicable; use mutex to protect errno reading
Dead Ends
Common approaches that don't work:
-
Ignoring the return value of C function
90% fail
No error handling at all.
-
Using `C.errno` directly without thread safety
60% fail
errno is thread-local in C, but Go may not preserve it.