gpt4 book ai didi

struct - cgo 从 Go : underscore or no underscore? 访问 C 结构字段

转载 作者:IT王子 更新时间:2023-10-29 01:42:38 28 4
gpt4 key购买 nike

我遇到了在线文档与我在程序中看到的在 GO 代码中访问 C 结构的行为之间的脱节。 go version 说我正在使用:

go version go1.4.2 linux/amd64

根据GO CGO documentation :

Within the Go file, C's struct field names that are keywords in Go can be accessed by prefixing them with an underscore: if x points at a C struct with a field named "type", x._type accesses the field. C struct fields that cannot be expressed in Go, such as bit fields or misaligned data, are omitted in the Go struct, replaced by appropriate padding to reach the next field or the end of the struct.

我遇到了麻烦,所以制作了一个快速示例程序来测试它:

package main
// struct rec
// {
// int i;
// double d;
// char* s;
// };
import "C"
import "fmt"
func main() {
s := "hello world"
r := C.struct_rec{}
r.i = 9
r.d = 9.876
r.s = C.CString(s)
fmt.Printf("\n\tr.i: %d\n\tr.d: %f\n\tr.s: %s\n",
r.i,
r.d,
C.GoString(r.s))
}

当我按照文档指示使用下划线时(例如,将 r._i 替换为上面的 r.i),我得到以下编译错误:

r._i undefined (type C.struct_rec has no field or method _i)

当我不使用下划线时它工作正常。我用指针和非指针都试过了。我唯一能想到的另一个想法是,也许是因为我在 GO 而不是 C 中分配了实例,是这样吗??

感谢您的帮助!

最佳答案

答案就在您问题中的引述中:

Within the Go file, C's struct field names that are keywords in Go can be accessed by prefixing them with an underscore(…)

ids 不是 Go 中的关键字。

关于struct - cgo 从 Go : underscore or no underscore? 访问 C 结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31163866/

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