我在学习Go语言方面还很陌生,并且我开始对此非常感兴趣
语言。
希望很快我会成为一个好地鼠。目前,我尝试调用C函数
读取影子文件,我的代码是:
// #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
}
受这个小项目和功能文档的启发
类(class):
https://github.com/LTD-Beget/passwd
http://linux.die.net/man/3/getspnam
我使用的是Debian Strand,并随包管理器一起安装了1.6版。
尝试编译文件时出现错误:
could not determine kind of name for C.getspnam_r
但是当我打开头文件shadow.h时,该功能就存在于
文件。
最佳答案
我纠正了我的错误。错误是使用了标志,一些是不必要的,以及结构名称的错字:
// #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
}
新版本的代码。
关于c - 从头开始调用C函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38790092/