dpr77335 2017-07-24 13:50
浏览 77
已采纳

如何在go包之间传递C对象?

When I try to pass a C.int from package main to a function in a helper package called common, I get the following error:

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

From common.go:

/* 
    ...
*/
import "C"

...

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

From 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)
    ...
}

Is there any way to pass these objects back and forth? I've tried type casting to e.g. common.C.int, but that doesn't seem to be valid syntax. I'd like to be able to call GoStrings from multiple different main programs, and it seems like that should be allowable.

  • 写回答

1条回答 默认 最新

  • douxu5845 2017-07-24 14:02
    关注

    Unfortunately you can't pass C types between packages. You'll need to perform any necessary type conversions within the package that is importing the C types. As per the 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.

    If you have common C translation methods that you use, consider using go generate with a helper script to create these in each package where it is required from a master source file. Not as nice as solution as having a common library but much better than manually updating files in multiple packages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!