【发布时间】:2016-09-08 04:15:03
【问题描述】:
我有一个通过 cgo 调用 Go 例程的 C 函数。我需要执行例程来正确设置 errno,以便 C 线程可以检查它的 errno 并采取相应措施。无法谷歌如何通过 Go 设置 errno
【问题讨论】:
我有一个通过 cgo 调用 Go 例程的 C 函数。我需要执行例程来正确设置 errno,以便 C 线程可以检查它的 errno 并采取相应措施。无法谷歌如何通过 Go 设置 errno
【问题讨论】:
澄清一下,你仍然可以通过你通过 cgo 调用的 C 函数来设置它。
package main
// #include <errno.h>
// #include <stdio.h>
//
// void setErrno(int err) {
// errno = err;
// }
//
import "C"
func main() {
C.setErrno(C.EACCES)
C.perror(C.CString("error detected"))
C.setErrno(C.EDOM)
C.perror(C.CString("error detected"))
C.setErrno(C.ERANGE)
C.perror(C.CString("error detected"))
}
在我的系统上它输出
error detected: Permission denied
error detected: Numerical argument out of domain
error detected: Numerical result out of range
【讨论】:
你不能直接从 go 中引用 errno,见cgo doesn't like errno on Linux。从那个线程:
我不知道出了什么问题,但这没关系,因为那不是 无论如何安全使用errno。对 C 的每次调用都可能发生在 不同的OS线程,这意味着直接引用errno是 不保证能得到你想要的值。
截至3880041 尝试引用C.errno 将引发错误消息:
cannot refer to errno directly; see documentation
作为pointed out in another answer,从 C 函数设置它是可行的。
【讨论】: