亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang (cgo) - 支持帶有 cgo 的嵌套結構嗎?

Golang (cgo) - 支持帶有 cgo 的嵌套結構嗎?

Go
海綿寶寶撒 2021-06-09 13:47:58
我試圖使用 cgo 為 x264 庫編寫一個小包裝器,但遇到了嵌套結構的問題。該庫使用了許多復雜的結構,其中一些字段本身就是匿名結構。當嘗試使用 cgo 訪問這些結構時,我遇到了編譯錯誤,因為 go 聲稱嵌套結構不存在。我設法將問題歸結為一個 .h 文件和一個粘貼在下面的 .go 文件。希望這足夠清楚以顯示問題。有誰知道這個問題的解決方案或解決方法?謝謝。結構體.htypedef 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.gopackage 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 回答

?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

你用的是什么版本的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如果您仍然遇到問題,您也可以像我一樣嘗試手動運行,看看它會生成什么。


查看完整回答
反對 回復 2021-06-28
  • 2 回答
  • 0 關注
  • 288 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號