Skip to content

Rust Construct Struct with Array Member at runtime

This is the question Construct structure with array member during runtime during runtime?

During FFI, I want to know the layout of structure and then this temporary structure will be discarded when function returns. However, the rustc rejects this case because the array size n is not a constant during the compiling time, even though the structure is defined for layout calculation.

use std::alloc::Layout;
pub(crate) fn sample_layout<Header, Payload>(n: usize) -> Layout
where
    Header: Sized,
    Payload: Sized,
{
    #[repr(C)]
    struct Sample<Header, Payload, const N: usize> {
        _header: Header,
        _payload: [Payload; N],
    }

    Layout::new::<Sample<Header, Payload, n>>()
}

It's impossible for function sample_layout1 to require a constant generic argument because the value might come from the configuration file.

pub(crate) fn sample_layout1<Header, Payload, const N: usize>()

The proper approach is to use the Layout to calculate the result as if a temporary structure is defined.

use std::alloc::Layout;
pub(crate) fn sample_layout<Header, Payload>(n: usize) -> Layout
where
    Header: Sized,
    Payload: Sized,
{
    let layout_header = Layout::new::<Header>();
    let layout_array = Layout::array::<Payload>(n).ok().unwrap();
    layout_header
        .extend(layout_array)
        .ok()
        .unwrap()
        .0
        .pad_to_align()
}