Skip to content

Instantly share code, notes, and snippets.

@caelifer
Created July 14, 2016 18:06
Show Gist options
  • Save caelifer/f037691db307c23f9fac03ec0d458ad7 to your computer and use it in GitHub Desktop.
Save caelifer/f037691db307c23f9fac03ec0d458ad7 to your computer and use it in GitHub Desktop.
How to handle errno from Go program via cgo.
package main
import "unsafe"
/*
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern int errno;
static void setErrno(int err) {
errno = err;
}
*/
import "C"
func main() {
msg := C.CString("error detected")
for _, en := range []C.int{C.EACCES, C.EDOM, C.ERANGE} {
C.setErrno(en)
C.perror(msg)
}
C.free(unsafe.Pointer(msg))
}
@caelifer
Copy link
Author

From this discussion

Sample output:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment