Search code examples
gocgo

How do I set errno from Go


I have a C function calling a Go routine via cgo. I need to Go routine to set the errno correctly so the C thread can inspect it's errno and act accordingly. Unable to google on how to set the errno via Go


Solution

  • Just to clarify, you can still set it via C-function that you call via cgo.

    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"))
    }
    

    On my system it outputs

    error detected: Permission denied
    error detected: Numerical argument out of domain
    error detected: Numerical result out of range