How to consolidate two struct initialization methods when dealing with FFI
⚓ Rust 📅 2025-12-10 👤 surdeus 👁️ 3Hi, I'm trying to do something in a no_std environment with no allocator. I basically have this struct as an interface to some hardware, and underneath it calls some platform C APIs. The APIs expect me to provide a pointer to a C struct for initialization stuff, and once it has gone through all the initialization APIs, the address of the C struct must stay the same.
Because of this, I wasn't sure how to write a single new() that handles both returning the struct and properly initializing it with the platform APIs in one go. On return from new(), the value will be moved to the caller, and the underlying addresses of the C struct will change. Thus, I have one method for just returning an instance of the type in an unknown state, and another for setting it to a proper state:
impl HardwareDriver {
pub fn new() -> Self {
Self {
device: core::mem::MaybeUninit::<HardwareThing>::uninit(),
},
}
pub fn initialize(&mut self) -> Result<(), ()> {
// Call C APIs here
}
}
Is there a better way of handling this so that it's just new() -> Result<Self, ()> and initialize() can go away? This used to be written in C++ and with the way C++ constructors worked (no copying out memory to the caller), it used to be that it was done in one go.
Or at least, if I can't consolidate the methods, is there a good way of forcing compile-time errors if a user calls other APIs before calling initialize()?
thanks ![]()
3 posts - 3 participants
🏷️ Rust_feed