加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:29:07 所属栏目:大数据 来源:网络整理
导读:我试图使用cgo为x264库编写一个小包装器,并遇到了嵌套结构的问题.该库使用了许多复杂的结构,其中一些字段本身就是匿名结构. 当尝试使用cgo访问这些结构时,我遇到了编译错误,因为声称嵌套结构不存在. 我已经设法将问题归结为.h文件和下面粘贴的.go文件.希望这
我试图使用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;

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}}
}

解决方法

您使用的是什么版本的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
}

当我修改你的程序以正确地refr到c和d嵌套在anon字段中并取消注释其他语句时,程序编译并运行最终语句打印结构为.

main._Ctype_param_struct_t{a:0,anon:main._Ctype_struct___0{c:0,d:0},e:0,anon2:main._Ctype_struct___1{f:0,g:0}}

如果您使用的是较旧版本的Go,也许可以尝试升级.您也可以像我一样手动运行cgo,以便在遇到问题时查看它产生的结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读