Internal ABI and external binary contracts
Internal ABI and external binary contracts
An application binary interface (ABI) specifies machine-level conventions such as argument passing, registers, alignment and symbol names. Go internal ABI is compiler-specific and may change between versions; it is not the C ABI. A public Go signature alone does not make a stable C entry point. Use cgo-generated wrappers and the generated C header. Here a fixed-width C type gives the boundary an explicit width.
package main
/*#include <stdint.h>static uint32_t plus(uint32_t x, uint32_t y) { return x+y; }*/import "C"import "fmt"
func main() { fmt.Println(C.plus(C.uint32_t(40), C.uint32_t(2))) }The wrapper converts and calls the native function according to the host ABI. uint32_t has exactly 32 bits. Do not equate Go int with C int or long across targets. Agree on signedness, ownership, length and errors as well as width. Consumers of c-shared should compile against the generated header.
Expected output:
42Memory layout is not a wire format
package main
import ( "encoding/binary" "fmt" "unsafe")
func main() { type Record struct { Kind uint8 Count uint32 } r := Record{1, 42} b := make([]byte, 5) b[0] = r.Kind binary.BigEndian.PutUint32(b[1:], r.Count) fmt.Printf("%x\n", b) fmt.Println(unsafe.Sizeof(r) >= uintptr(len(b)))}Padding and alignment may make the in-memory struct larger than its fields. A serialized record explicitly defines byte order and field offsets; it remains independent of host layout. Never serialize uninitialized padding or reinterpret arbitrary foreign bytes as Go pointers.
Expected output:
010000002atrueTry it locally
Decode exactly five bytes: a one-byte kind followed by a big-endian uint32. Reject shorter or longer inputs before indexing. Test valid data and a truncated record.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Native interoperability 04: Internal ABI and external binary contracts
Check the lesson objective before moving on.
Why compile C consumers against a cgo-generated header?
Why define a wire byte order instead of dumping a struct?