Generically pass Rust smart pointers via C's `void *`

I have a C library that accepts data as C void * (sometimes with a size), and I'd like to expose an interface that exposes a generic type-checked interface. I thought that I could write a trait for types that can be transformed to a C void * and back, such as &'static T and Box<T>, but also usize and Rc<T>. My first question is whether there is a crate that already provide something similar (I didn't find one).

Then, if there's no crate that I can use, I'd also like some feedback on my current design for this. I'm thinking about using two traits for thin and fat pointers respectively (as the library sometimes accepts a size along the void pointer). Each trait would have methods to convert to and from void *, and a method to obtain a reference to the value from a void *. There likely would be a blanket impl of the fat pointer trait for types implementing the thin pointer one. I'm also wondering about using a third super trait to convert to a void * and size, instead of duplicating these functions in the two other traits, or having to manually implement both traits for thin pointers.

Until Pointee is stabilized I'm not sure a crate could usefully provide generic impls for traits like that, since whether or not a pointer type is thin or fat depends on a type parameter.

Thanks for your reply. While being able to express Pointee<Metadata = usize> and use ptr::from_raw_parts would be helpful, I don't think that's it necessary for a library to be useful. Thin pointer support can already be implemented generically, and by itself that would already be useful. Then an impl for [T] and str cover most fat pointers. dyn Trait likely would still be impossible to support, unless DynMetadata can be converted to and from an usize.

Oh you're right, I forgot about Sized somehow :man_facepalming:

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.