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

Fre*_*rik 5 c struct go cgo

我试图使用cgo为x264库编写一个小包装器,并遇到了嵌套结构的问题.该库使用了许多复杂的结构,其中一些字段本身就是匿名结构.

当尝试使用cgo访问这些结构时,我遇到了编译错误,因为声称嵌套结构不存在.

我已经设法将问题归结为.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;
Run Code Online (Sandbox Code Playgroud)

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}}
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*dge 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
}
Run Code Online (Sandbox Code Playgroud)

当我修改您的程序以正确引用cd嵌套在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}}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本的 Go,也许可以尝试升级。如果仍然遇到问题,您也可以像我一样尝试cgo手动运行,看看它生成了什么。