Search code examples
cgodebianshadow

Call a C function from go


I'm quite new on learning go language, and I start to be a great lover of this language. I hope, I will be a good gopher soon. Currently I try to call a C function to read the shadow file, my code is:

// #cgo CFLAGS: -D_POSIX_SOURCE=1
// #include <stdlib.h>
// #include <shadow.h>
// size_t size_of_shadow() { return sizeof(struct spwd); }
import "C"
import "unsafe"
import "fmt"

type Shadow struct {
    Name   string
    Passwd string
}

func Getspnam(name string) (*Shadow, error) {
    cname := C.CString(name)
    cspwd := (*C.struct_passwd)(C.malloc(C.size_of_shadow()))
    buf := (*C.char)(C.malloc(1024))
    _, err := C.getspnam_r(cname, cspwd, 1024, &cpwd)

    if unsafe.Pointer(cspwd) == unsafe.Pointer(uintptr(0)) {
        C.free(unsafe.Pointer(cname))

        if err == nil {
            err = fmt.Errorf("User %s not found", name)
        }

        return nil, err
    }

    s := Shadow{
        Name: C.GoString(cspwd.sp_namp),
        Passwd: C.GoString(cspwd.sp_pwdp),
    }

    C.free(unsafe.Pointer(cname))
    C.free(unsafe.Pointer(cspwd))
    C.free(unsafe.Pointer(buf))

    return &s, nil
}

Inspired by this little project and the documentation of the function of course:

https://github.com/LTD-Beget/passwd http://linux.die.net/man/3/getspnam

I'm on debian stretch and go 1.6 version, installed with the package manager. I got an error when I try to compile my file:

could not determine kind of name for C.getspnam_r

But when I open the header file shadow.h, the function is however present on the file.


Solution

  • I fixed my mistake. The error was the used of the flag some was unnecessary and the typo on the name of the struct:

    // #include <stdlib.h>
    // #include <shadow.h>
    // size_t size_of_shadow() { return sizeof(struct spwd); }
    import "C"
    
    import "C"
    import "unsafe"
    import "fmt"
    
    type Shadow struct {
        Name   string
        Passwd string
    }
    
    func Getspnam(name string) (*Shadow, error) {
        cname := C.CString(name)
        defer C.free(unsafe.Pointer(cname))
    
        cspwd := (*C.struct_spwd)(C.malloc(C.size_of_shadow()))
        defer C.free(unsafe.Pointer(cspwd))
    
        buf := (*C.char)(C.malloc(1024))
        defer C.free(unsafe.Pointer(buf))
    
        _, err := C.getspnam_r(cname, cspwd, buf, 1024, &cspwd)
    
        if unsafe.Pointer(cspwd) == unsafe.Pointer(uintptr(0)) {
            if err == nil {
                err = fmt.Errorf("User %s not found", name)
            }
    
            return nil, err
        }
    
        s := Shadow{
            Name:   C.GoString(cspwd.sp_namp),
            Passwd: C.GoString(cspwd.sp_pwdp),
        }
    
        return &s, nil
    }
    

    The new version of the code.