C语言 使用 cgo 构建共享对象时导出变量



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

var (
Gval1 int
Gval2 string
//GvalN
)
func f(){
Gval1 = 1
Gval2 = "qwerty"
}

.so lib 的客户端将运行 f((;之后,它可以通过寻址变量的名称来获取变量。如何导出它们? 我曾尝试过做这样的技巧:golang cgo 无法通过构建模式 c-shared 导出变量,但没有成功(示例始终返回 0,而不是 42(。 如何导出变量(数字和字符串(?

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

go构建文档说:

-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 文档说的地方

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

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

最新更新