Golang(cgo)- cgo支持嵌套结构体吗?

5
我正在尝试使用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}}
}
2个回答

2
你使用的是哪个版本的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
}

当我修改您的程序以正确引用嵌套在“anon”字段中的“c”和“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以查看它正在生成什么。


我正在运行go 1.2rc2,这可能解释了问题。当使用go tool cgo main.go输出类型时,我得到了一个像这样的结构体:type _Ctype_struct_param_struct_t struct { //line :1 a _Ctype_int //line :1 b _Ctype_int //line :1 c _Ctype_int //line :1 d _Ctype_int //line :1 _ [12]byte //line :1 } - Fredrik
在这种情况下,听起来像是一个 bug。最好在 bug 跟踪器或邮件列表中报告它。 - James Henstridge
通过降级到go1.1.2,它确实已经解决了。 - Fredrik

0

我不熟悉cgo。但是你不能直接在go代码中使用C类型,因为cgo重新生成了自己的类型。也许它是_C_param_struct_t。

请参考这份官方文档:http://golang.org/misc/cgo/gmp/gmp.go


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接