I have the following scenario and goals:
- Implement a library in Rust that has to be shared by many binaries
- Keep the size of the binary as small as possible
As far as I know, a way to get it is:
- Compile the library with
crate-type = "dylib"
. This generates the desired .so library - Use the crate libloading to dynamically access the library objects from within a binary.
I successfully implemented a very basic example and the size of the compiled files are small enough. Here's the code:
lib.rs
#[no_mangle]
pub fn minicall() -> u8 {
3u8
}
main.rs
fn main() {
unsafe {
let lib = libloading::Library::new("liblibtest.so").unwrap();
let func: libloading::Symbol<unsafe extern fn() -> u32> = lib.get(b"minicall").unwrap();
let r = func();
println!("r = {r}");
}
}
Now, I need to expand my example by adding types and method to the lib, for example:
lib.rs
pub struct User {
username: String,
email: String,
}
impl User {
fn new(username: String, email: String) -> User {
User {
username,
email
}
}
}
#[no_mangle]
pub fn minicall() -> u8 {
3u8
}
and then, use them in my binary:
main.rs
fn main() {
unsafe {
let lib = libloading::Library::new("liblibtest.so").unwrap();
let func: libloading::Symbol<unsafe extern fn() -> u32> = lib.get(b"minicall").unwrap();
let r = func();
println!("r = {r}");
let user = ???? <----------------------
}
}
How can I get access to types and methods in the library? Please note that evereything is in Rust, no C is involved.