开源分享 · 2023年9月18日

Using C/C++ compatible structs in Java easily

In C/C++, we usually use struct to parse file headers or communication packets. But doing same works is painful in Java, we must write many lines of code to do it. Structs4Java may help you.

https://github.com/marc-christian-schulze/structs4java

Note: 1、Adding the Getting Started mentioned plugin configuration to <build><plugins>….</plugins></build> sections in pom.xml, not to<pluginManagement><plugins>…</plugins></pluginManagement> sections, it cost me almost a day to figure it out.

2、If you are using Intellij IDE, to use generated struct class, just mark the folder named “structs-gen” with “generated sources root”, which will auto-generated after maven plugin->structs4java->compile plugin executed.

 

Structs4Java is a code generator that is based on structure definitions very similiar to C/C++ but with some subtle differences. Unlike in C/C++,

  • structs have a defined memory layout (no automatic alignment/packing),
  • structs can have a dynamic size (we support dynamic arrays)
  • but we do not support unions.

Its purpose is to provide an easy and portable way to read/write legacy file formats that are typically described as C/C++ structures. For each struct and enum declaration the code generator will produce a corresponding Java class with a read and write method accepting a java.nio.ByteBuffer.