Rust / C FFI structs

I have a bit of an interesting situation that I'm looking for a better solution to. Right now I copy data around, but it's not the best solution.

I have the following C structs that I need to interact with:

struct hdr {
Int field1;
Char field2;
...
char data[1];
};

Hdr.data could be start of a new struct (there's about 30 to choose from) or the start of payload, depends on some of the fields in the header.

What I get is an array of u8 that should be converted to / from all this.

What is the most effective way of doing this in Rust, both reading data into various structs as well as dumping data from various structs.

At first I tried replicating the above, and dropping the hdr.data, but that comes with padding issues ofc.

Right now I'm dumping to / from an u8 array and into different structs, but that means a lot of memcopy.

Any guidance would be mostly appreciated.

for simple cases, rust has repr(C) enums, but in general, tricky to model what I would like to call "internally discriminated sum type" in a way that feels natural and idiomatic in rust. I would typically just make the ffi data structures declared as distinct types, then create a rust enum to sum them up. it works pretty well in practice.

you should properly parse/deserialize the bytes into strongly typed value, instead of clever type-punning.

did you measure the code's performance? are you sure the memcpy-es are the bottle neck? personally, I would just go the simple route and not preemptively micro-optimize in such cases.

that being said, if you do need to eliminate the copies, you can always parse the bytes "in-place" and return borrowed data, given the data layout is really compatible (e.g. alignment, padding, etc).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.