Java JNA: Unexpected struct packing size with nested union - Stack Overflow

admin2025-04-10  1

I am creating a JNA (5.16) interface to V4L2 running on a Raspberry Pi 5 (Debian aarch64). Most of the structs map well, but v4l2_format is undersized at 204 compared to C sizeof 208. The offset of the union fmt is 4 in Java, 8 in C. The alignment is default. Using OpenJDK 64-bit 23.0.1.

Any ideas to fix the packing?

struct v4l2_format {
    __u32    type;
    union {
        struct v4l2_pix_format pix;
        struct v4l2_pix_format_mplane pix_mp;
        struct v4l2_window win;
        struct v4l2_vbi_format vbi;
        struct v4l2_sliced_vbi_format sliced;
        struct v4l2_sdr_format sdr;
        struct v4l2_meta_format meta;
        __u8 raw_data[200];
    } fmt;
};

sizeof(struct v4l2_format) = 208 // 204 in Java
sizeof(struct v4l2_format.fmt) = 200 // 200 in Java
offsetof(struct v4l2_format,fmt) = 8 // 4 in Java
import com.sun.jna.Structure;
import com.sun.jna.Structure.FieldOrder;
import com.sun.jna.Union;

public class V4l2 {
    
    @FieldOrder({ "raw_data" })
    public static class v4l2_format_fmt extends Union {
        // simplified
        public byte[] raw_data = new byte[200];
    }

    @FieldOrder({ "type", "fmt" })
    public static class v4l2_format extends Structure {
        public int type;
        public v4l2_format_fmt fmt;
    }

    public static void main(String[] args) {
        System.out.println("sizeof(v4l2_format) = " + new v4l2_format().size()); // 204
        System.out.println("sizeof(v4l2_format_fmt) = " + new v4l2_format_fmt().size()); // 200
    }
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744257434a238384.html

最新回复(0)