Skip to content

cmd/cgo: doesn't support struct with bit fields #43261

Description

@mengzhuo

What version of Go are you using (go version)?

$ go version
eaa97fbf20baffac713ed1b780f864a6fee54ab6

Does this issue reproduce with the latest release?

no

What did you do?

package main

/*
struct foo {
        int bf:4;
        int bar;
};
*/
import "C"

import (
        "unsafe"
)

func main() {
        a := [24]byte{}
        c := (*C.struct_foo)(unsafe.Pointer(&a))
        c.bar = '4'
        c.bf = 1
        print(string(a[:]))
}

What did you expect to see?

go build passed

What did you see instead?

c.bf undefined (type *_Ctype_struct_foo has no field or method bf)

This is just a demo.

In https://go-review.googlesource.com/c/go/+/252378

cgo no longer try to translate
C struct bitfields into Go struct fields, even if their size can be
represented in Go. The order in which C bitfields appear in memory
is implementation dependent, so in some cases the cgo tool produced
results that were silently incorrect.

In real life, some system api like ebpf <linux/bpf.h> do has struct with bit fields.

struct bpf_insn {
        __u8    code;           /* opcode */
        __u8    dst_reg:4;      /* dest register */
        __u8    src_reg:4;      /* source register */
        __s16   off;            /* signed offset */
        __s32   imm;            /* signed immediate constant */
};

Related:
xlab/c-for-go#109

Maybe we should reconside it?
Thanks

CC @ianlancetaylor

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions