Skip to content

How do I ensure alignment between Go and C structs? #857

Answered by ti-mo
binw666 asked this question in Q&A
Discussion options

You must be logged in to vote

There are many resources and tools available to work with Go struct alignment, and yes, it's something you need to pay attention to when sharing them between C and Go. The Go struct you pasted here seems to be 28 bytes long on a 64-bit architecture: https://go.dev/play/p/u4X0Vn-finI. Hint: run it through structslop to optimize its size.

The following C program also evaluates to 28:

#include <stdio.h>

typedef unsigned char __u8;
typedef short unsigned int __u16;
typedef unsigned int __u32;
typedef long long unsigned int __u64;

struct ip_tcp_rule{
    __u8 flag;
    __u32 src_ip;
    __u8 src_ip_mask;
    __u32 dst_ip;
    __u8 dst_ip_mask;
    __u8 min_ttl;
    __u8 max_ttl;
    __u16 sr…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by ti-mo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants