r/cprogramming • u/SheikHunt • Jun 11 '26
Best practices for interoperability between C structs and other languages?
Apparently, there exists a program that can turn some C programs into Rust ones, more specifically it can be used to make C structs usable in Rust.
I am writing an HTTP server that, with this feature, its usability would be far better than otherwise. Specifically, there is an http.h file that includes all necessary information for some other language to use to understand a struct and its values.
With that said, should I use C's types (short, int, long, etc.) Which you famously never know how big they are, or should I use the types given by <stdint.h> and any similar header files that give you portable-ish int sizes?
Also, bonus question: Does any version of the described program exist for other languages? One that can take some C code relating to structs, or a compiled object file or other binary that contains information about a struct and maybe even the enums used therein, and produce a language-appropriate version of that struct for ease of use?
7
u/somewhereAtC Jun 11 '26
There isn't even a best-practice for interoperability between different C compilers on different machines.
My best practice is to use <stdint.h> for everything, define the layout using clear illustrations and review carefully when porting to a new platform. At some point I don't think of it as a "C structure" but as a C implementation of the data format defined for what I'm doing (e.g., Ethernet packets).
4
u/WittyStick Jun 12 '26
Even with stdint, the struct layout is implementation defined and may vary between ABIs.
You can provide some attributes to assist with portability. GCC has
ms_structfor example to have structs compatible with MSVC, and functions with these in their signature should also probably use thems_abiattribute (default on mingw).The best option for portability is to have proper serialization and deserialization functions, but if you need ABI compatibility it needs to be able to target multiple platforms.
2
u/Interesting_Debate57 Jun 13 '26
You can look up protobuffs. They'll give you an idea of one approach.
2
u/pjl1967 Jun 12 '26
You should follow what the Rust folks have taken the time to explicitly write about using C from Rust; see here; for using C memory layout from Rust, see here.
1
u/DawnOnTheEdge Jun 12 '26
Follow the foreign function interface for your platform. Exact-width types such as
uint32_tare your best bet for ABI portability.0
u/ByMeno Jun 11 '26
Imo stdint is safer and for using c in other languages most of the use C forgein function interface ffi in short search for that you may find better results