Getting C-compatible structs in Go with and for cgo
utcc.utoronto.ca
utcc.utoronto.ca
https://common-lisp.net/project/cffi/manual/html_node/defcst...
When I asked about why going cgo instead, the general reaction was "go away we know better", as usual.
EDIT: Typo (way => away)
> (By the way, I do mean 'Sysinfo' here, not 'Cpu_sysinfo'. Cgo is smart enough to take that sort of commonly seen prefix off of struct field names. I don't know what its algorithm is for doing this, but it's at least useful.)
Anyone know why cgo does this? This seems like an anti-feature to me – if I want fields with prefixes that are different from the C ones, at least make that a knob (and preferably one that isn't turned on by default).
// +build ignore
package tmp
/*
#include <btrfs/ctree.h>
*/
import "C"
// 220 struct btrfs_disk_key {
// 221 __le64 objectid;
// 222 u8 type;
// 223 __le64 offset;
// 224 } __attribute__ ((__packed__));
type BtrfsDiskKey C.struct_btrfs_disk_key
Output: $ go tool cgo -godefs test.go
// Created by cgo -godefs - DO NOT EDIT
// cgo -godefs test.go
package tmp
type BtrfsDiskKey struct {
Objectid uint64
Type uint8
Pad_cgo_0 [8]byte
}
After all the experiments I created my own helper[1], which helps map C structure(even packed) to Go structure using reflect package.[1] https://github.com/plar/btrfs/blob/master/ioctl/mappings.go
It's somewhat sad that LuaJIT (effectively a one man project) contains a FFI interface with a hand-crafted lexer and tokenizer that supports the packed attribute correctly.