Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Erasing struct generics where there are no sized fields using them #1045

Open
analogrelay opened this issue Jan 18, 2025 · 0 comments
Open

Comments

@analogrelay
Copy link

In the C API I'm building, I'd like to have this struct:

pub struct FfiSlice<'a, T> {
    ptr: *const std::ffi::c_void,
    len: usize
    phantom: std::marker::PhantomData<&'a T>,
}

The idea is to wrap up the pointer and length of an array that's only valid for the duration of a given API call, and is expected to be an array of T (where T is some FFI-safe value). The lifetime 'a and type T are there to enforce those rules throughout the Rust code, though they have no effect at the FFI boundary:

extern "C" fn some_api<'a>(bytes: FfiSlice<'a, u8>) {
    let bytes: &'a [u8] = unsafe { bytes.as_slice().unwrap() };
    // ...
}

When I use cbindgen to generate this, the FfiSlice struct is monomorphized into FfiSlice_u8, which normally makes sense but there's no need to monomorphize it at all because the layout is the same no matter the T. The T is only used in zero-sized fields within the struct. The generic parameter can be erased entirely.

Is there a way to instruct cbindgen to do this? I get that maybe it can't detect this scenario, but could there be an option to "erase" generics from a given type (at your own risk)?

@analogrelay analogrelay changed the title Erasing struct generics where there are no fields using them Erasing struct generics where there are sized fields using them Jan 18, 2025
@analogrelay analogrelay changed the title Erasing struct generics where there are sized fields using them Erasing struct generics where there are no sized fields using them Jan 21, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant