When using cgo to generate Go structs, some fields are ignored in the definition.

100 views
Skip to first unread message

飞舟

unread,
Jul 24, 2024, 7:29:39 AMJul 24
to golang-nuts

I have a C struct, and when I use cgo to generate Go structs, some fields are being ignored. I’m using go version go1.21.1 linux/amd64, and here is my env.

go env:

GO111MODULE='on'
GOARCH='amd64'
GOBIN=''
GOCACHE='/root/.cache/go-build'
GOENV='/root/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/root/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/root/go'
GOPRIVATE=''
GOPROXY='https://goproxy.cn,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.21.1'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='1'
GOMOD='/dev/null'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/go-build2970417006=/tmp/go-build -gno-record-gcc-switches'

and this is my C struct:

typedef struct PicHead
{
unsigned short flag;
unsigned char version[16];
unsigned int headSize;
int64_t fileSize;
unsigned int macrograph;
unsigned int personInfor;
unsigned int hierarchy;
unsigned int srcWidth;
unsigned int srcHeight;
unsigned int sliceWidth;
unsigned int sliceHeight;
unsigned int thumbnailWidth;
unsigned int thumbnailHeight;
unsigned char bpp;
unsigned char quality;
J_COLOR_SPACE colrSpace;
float scale;
double ruler;
unsigned int rate;
long long extraOffset;
long long tileOffset;
ImageFormat sliceFormat;
unsigned char headSpace[48];
}PicHead;

this is cgo gen

type _Ctype_struct_PicHead struct {
flag _Ctype_ushort
version [16]_Ctype_uchar
_ [40]byte
bpp _Ctype_uchar
quality _Ctype_uchar
colrSpace _Ctype_J_COLOR_SPACE
scale _Ctype_float
_ [8]byte
rate _Ctype_uint
extraOffset _Ctype_longlong
tileOffset _Ctype_longlong
sliceFormat _Ctype_ImageFormat
headSpace [48]_Ctype_uchar
}
Message has been deleted

Ian Lance Taylor

unread,
Jul 24, 2024, 8:32:34 AMJul 24
to 飞舟, golang-nuts
On Wed, Jul 24, 2024 at 5:29 AM 飞舟 <[email protected]> wrote:
>
> I have a C struct, and when I use cgo to generate Go structs, some fields are being ignored. I’m using go version go1.21.1 linux/amd64, and here is my env.

Please post code as plain text, rather than with a background. Plain
text is much easier to read. Thanks.

Also, please show us a complete, small, example. I tried your
example. I had to invent types for J_COLOR_SPACE and ImageFormat. It
worked fine.

Does your actual code use anything like #pragma packed? That will
cause this kind of problem, as Go does not currently have any way to
represent a packed struct.

Ian
Reply all
Reply to author
Forward
0 new messages