cgo不会在导入的包中导出函数 [英] cgo doesn't export functions in imported packages
问题描述
我正在尝试使用 CGO 将现有的Go程序包构建到C共享库和标头中.
I'm trying to build existed Go package into C shared library and header using CGO.
我使用记录的 -buildmode c-shared
构建了程序包.
I built the package with -buildmode c-shared
as documented.
-buildmode=c-shared
Build the listed main package, plus all packages it imports,
into a C shared library. The only callable symbols will
be those functions exported using a cgo //export comment.
Requires exactly one main package to be listed
并使用//export Func
将函数公开为C符号.
And used //export Func
to expose functions as C symbols.
main
包中的所有//export
函数均已正确导出.但是,当我将这些功能移到子包(带有//export
)时,这些功能不会导出.我也将子包导入了 main
包中.
All //export
functions in main
package are exported properly. However when I moved those functions to sub-package (with //export
), those functions are not exported. I imported the sub-package in main
package, too.
这是我的代码.
main.go
package main
import "C"
import (
"fmt"
_ "github.com/onosolutions/archanan-cgo/c"
"math/rand"
)
// FuncInMain generates a random integer.
//export FuncInMain
func FuncInMain(max C.int) C.int {
return C.int(rand.Intn(int(max)))
}
func main() {
fmt.Printf("Hello World %d!\n", int(FuncInMain(256)))
}
c/c.go
package c
import "C"
import (
"math/rand"
)
// FuncInSubPackage generates a random integer.
//export FuncInSubPackage
func FuncInSubPackage(max C.int) C.int {
return C.int(rand.Intn(int(max)))
}
然后仅导出 FuncInMain
.
我通读了 CGO文档,但是关于分包导出没有什么可说的.我获得的唯一线索是通过 go help buildmode
,但是它表示所有导入的子包都将被编译.我不确定是否不支持它,或者我错过了一些配置.
I read through CGO documentation, but there's nothing saying about exporting in sub-packages. The only clue I got is through go help buildmode
, but it said that all imported sub-packages will be compiled. I'm not sure whether it isn't supported or I missed some configurations.
我很想实现这一点,以便能够对//export
函数进行模块化.
I'd love to achieve that to be able to modularize //export
functions.
推荐答案
他们两个都有自己的 C.type
,据我所知,无法通过导入函数C.type
,但使用链接.
Both of them have own C.type
, so as far as I know, there's no way to import function with C.type
but using linking.
我没有尝试过,但是给了机会:
I didn't tried, but give it a chance:
import _ "unsafe"
//go:linkname FuncInSubPackage c.FuncInSubPackage
//export FuncInSubPackage
func FuncInSubPackage(max C.int) C.int
这篇关于cgo不会在导入的包中导出函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!