我试图使用cgo为x264库编写一个小包装,并遇到了嵌套结构的问题。该库使用许多复杂的结构,其中某些字段本身就是匿名结构。
当尝试使用cgo访问这些结构时,我遇到了编译错误,因为go声称嵌套结构不存在。
我设法将问题归结为下面粘贴的.h文件和.go文件。希望这一点足以说明问题。
有人知道该问题的解决方案或解决方法吗?
谢谢。
typedef struct param_struct_t {
int a;
int b;
struct {
int c;
int d;
} anon;
int e;
struct {
int f;
int g;
} anon2;
} param_struct_t;
package main
/*
#include "struct.h"
*/
import "C"
import (
"fmt"
)
func main() {
var param C.param_struct_t
fmt.Println(param.a) // Works and should work
fmt.Println(param.b) // Works and should work
fmt.Println(param.c) // Works fine but shouldn't work
fmt.Println(param.d) // Works fine but shouldn't work
// fmt.Println(param.e) // Produces type error: ./main.go:17: param.e undefined (type C.param_struct_t has no field or method e)
// fmt.Println(param.anon) // Produces type error: ./main.go:18: param.anon undefined (type C.param_struct_t has no field or method anon)
// The following shows that the first parameters and the parameters from the
// first anonymous struct gets read properly, but the subsequent things are
// read as seemingly raw bytes.
fmt.Printf("%#v", param) // Prints out: main._Ctype_param_struct_t{a:0, b:0, c:0, d:0, _:[12]uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}}
}
您正在使用哪个版本的Go?使用Go 1.1.2,cgo似乎产生了预期的输出。
我运行了go tool cgo main.go
,生成的_obj/_cgo_gotypes.go
文件包含以下定义:
type _Ctype_param_struct_t _Ctype_struct_param_struct_t
type _Ctype_struct___0 struct {
//line :1
c _Ctype_int
//line :1
d _Ctype_int
//line :1
}
type _Ctype_struct___1 struct {
//line :1
f _Ctype_int
//line :1
g _Ctype_int
//line :1
}
type _Ctype_struct_param_struct_t struct {
//line :1
a _Ctype_int
//line :1
b _Ctype_int
//line :1
anon _Ctype_struct___0
//line :1
e _Ctype_int
//line :1
anon2 _Ctype_struct___1
//line :1
}
当我修改您的程序以使其正确引用c
并d
嵌套在该anon
字段中并取消注释其他语句时,该程序将编译并运行,最后一条语句将结构打印为。
main._Ctype_param_struct_t{a:0, b:0, anon:main._Ctype_struct___0{c:0, d:0}, e:0, anon2:main._Ctype_struct___1{f:0, g:0}}
如果您使用的是旧版的Go,请尝试升级。cgo
如果您仍然遇到问题,也可以尝试像我一样手动运行,以查看生成的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句