gpt4 book ai didi

c - 使用 cgo 构建共享对象时导出变量

转载 作者:数据小太阳 更新时间:2023-10-29 03:10:53 26 4
gpt4 key购买 nike

我想使用带有选项 go build -buildmode=c-shared 的 Go/Cgo 构建一个 .so 库。函数导出良好,但我无法导出变量。我需要实现一个 API,它通过调用一个 void 函数来工作,该函数设置各种全局属性的值。像这样:

var (
Gval1 int
Gval2 string
//GvalN
)

func f(){
Gval1 = 1
Gval2 = "qwerty"
}

.so lib 的客户端将运行 f();之后,它可以通过寻址变量的名称来获取变量。我怎样才能导出它们?我曾尝试过这样的把戏:golang cgo can't export variables by build mode c-shared ,但没有成功(示例始终返回 0,而不是 42)。如何导出变量(数字和字符串)?

最佳答案

我不认为你可以导出变量,只能导出函数。

go build文档说:

-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

哪里cgo docs says

Go functions can be exported for use by C code in the following way:

我猜你可以写一个返回变量值的函数。

关于c - 使用 cgo 构建共享对象时导出变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52036061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com