2017-07-24 17 views
0

当我尝试从包main传递C.int给函数在一个辅助包叫做common,我得到以下错误:如何在go包之间传递C对象?

main.go:24: cannot use argc (type C.int) as type common.C.int in argument to common.GoStrings 

common.go

/* 
    ... 
*/ 
import "C" 

... 

func GoStrings(argc C.int, argv **C.char) (args []string) { 
    // do stuff 
} 

main.go

/* 
#cgo LDFLAGS: -lpam -fPIC 
#define PAM_SM_AUTH 

#include <security/pam_appl.h> 
*/ 
import "C" 

... 

func pam_sm_authenticate(pamh *C.pam_handle_t, flags, argc C.int, argv **C.char) C.int { 
    args := common.GoStrings(argc, argv) 
    ... 
} 

有什么办法来回传递这些对象吗?我已经尝试过将类型转换为例如common.C.int,但这似乎不是有效的语法。我希望能够从多个不同的主程序中调用GoStrings,看起来这应该是可以允许的。

回答

3

不幸的是,你不能在包之间传递C类型。您需要在导入C类型的包中执行任何必需的类型转换。由于每documentation

Cgo translates C types into equivalent unexported Go types. Because the translations are unexported, a Go package should not expose C types in its exported API: a C type used in one Go package is different from the same C type used in another.

如果您有使用常用的C翻译方法,可以考虑使用go generate用一个脚本在每个地方它是从一个主源文件所需的程序包来创建这些。没有解决方案那么好,而是比手动更新多个包中的文件要好得多。

+0

对于这种情况,我通常会传递'unsafe.Pointer'。这有效,但你最好确保做到理智和错误检查! –