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.

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序