我试图使用cgo为x264库编写一个小包装器,但遇到了一个嵌套结构的问题。库使用了许多复杂的结构,其中一些字段本身是匿名的。
当试图使用cgo访问这些结构时,我会运行编译错误,因为go声称嵌套结构不存在。
我已经成功地将问题归结为一个.h文件和下面粘贴的一个.go文件。希望这是足够清楚的,以显示问题。
有人知道这个问题的解决方案或解决办法吗?
谢谢。
struct.h
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;main.go
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}}
}发布于 2013-09-18 08:07:31
你用的是什么版本的围棋?使用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
}当我将您的程序修改为正确地将refr转换为嵌套在c字段中的anon和d并取消对其他语句的注释时,该程序编译并使用最后一条语句运行,最后的语句将结构打印为。
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,就像我所做的那样,看看如果仍然遇到问题,它会产生什么。
发布于 2013-09-18 07:58:56
我不熟悉cgo。但是,您不能直接将go代码中的C类型作为cgo来重新生成它自己的类型。也许是_C_param_struct_t。
请参阅以下官方文档:http://golang.org/misc/cgo/gmp/gmp.go
https://stackoverflow.com/questions/18866462
复制相似问题