Search code examples
gocgo

How do I pass an error message from C to Go?


I want to pass an error message from C code to Go stack. How I can accomplish this using an out parameter?

I'd really thankful if someone can help me.


Solution

  • Any C function (even void functions) may be called in a multiple assignment context to retrieve both the return value (if any) and the C errno variable as an error (use _ to skip the result value if the function returns void).

    Then in your c code all you have to do is to set the “global” errno variable.

    package main
    
    
    // #include <errno.h>
    // int fortytwo()
    // {
    //      errno = ENOENT;
    //      return 42;
    // }
    import "C"
    import "fmt"
    
    func main() {
    
        n, err = C.fortytwo()
    }