rust-bindgen icon indicating copy to clipboard operation
rust-bindgen copied to clipboard

Generating a dummy `dynamic-loading`-like struct when not using libloading

Open marcin-serwin opened this issue 4 months ago • 0 comments

Some crates have the ability to decide whether the shared object file will be dlopened or linked into the executable. For example, ash-rs exposes Entry::linked() and Entry::load() depending whether features linked or loaded were enabled. Achieving this with bindgen is currently possible but the exported symbols have different API which requires using conditional compilation whenever a function from the library is called, e.g.,

impl Foo {
    #[cfg(feature = "linked")]
    pub fn linked() -> Self {
        Self {}
    }
    #[cfg(feature = "loaded")]
    pub fn loaded() -> Self {
        Self {
            lib: FooLib::new("libfoo.so").unwrap(),
        }
    }

    pub fn mk_bar_wrapped(&self) {
        #[cfg(feature = "linked")]
        mk_bar();

        #[cfg(feature = "loaded")]
        self.lib.mk_bar();
    }
}

It would be if it were possible to emit a dummy FooLib struct with impl that ignores self and calls the exported function from the linked binary, something like:

impl FooLib {
    pub fn dummy() -> Self {
        Self { _unused: [] }
    }

    pub fn mk_bar(&self) {
        mk_bar()
    }
}

This way the mk_bar_wrapped implementation could be simplified to always call the mk_bar fn through the self.lib object regardless of whether libfoo is loaded or linked.

marcin-serwin avatar Aug 04 '25 14:08 marcin-serwin