Hi everyone,
I am asking you for some help because I'm facing an issue, trying to look for a solution but nothing cames out, here it is.
I am writing a Rust code which is interfacing with C code. On the C side, I got this structure:
typedef struct {
uint16_t event;
uint8_t data[];
} HEADER;
The data field can get any size, so I represented this structure in Rust like this:
#[repr(C)]
pub struct Header<T: ?Sized> {
pub event: u16,
pub data: T,
}
To malloc this struct in C side, I am doing it like that:
void foo() {
Header* hdr = (Header*) external_malloc(size_of(smth));
}
But I actually need to cast it in rust due to FFI safe issue ([u8] is not FFI safe). I am sending a void* data to rust instead and I need to cast it to Header.
To handle the data of this structure in Rust, here is how I proceed:
extern "C" {
// calling my personnal C malloc
fn external_malloc(size: usize) -> *mut c_void;
}
fn malloc_c_struct(size: usize) -> &'static mut Header<[u8]> {
/* I am facing an issue here, the cast is not as straightforward as it is in C*/
let p_header: &mut Header<[u8]> = unsafe { external_malloc(size) } as &mut Header<[u8]>;
p_header
}
What is the best way to cast my *mut c_void to &mut Header<[u8]>, something similar to the following C code:
Header* hdr = (Header*) external_malloc(size_of(smth));
Thank you very much for your help ! Hope i've been clear enough.