Any examples of dynamic linking of Rust code?

This may be a silly question.
But was wondering about being able to dynamically link rust code/libraries/etc ... at run time.

Can't really give you a good use case... :zipper_mouth_face:

I've done it in Java in the past... and if my memory is still good did it in C many,many moons ago.
(Early 90s. )

1 Like

Not a silly question, it would be pretty awesome.

If you're talking about doing it at the beginning of the program, it's probably possible, but hard. According to Linkage - The Rust Reference , you can compile with --crate-type=dylib. Unfortunately, Rust's ABI isn't stable so you can't load code between versions. I found this Reddit thread about it where people say it's possible but don't really explain how to do it.

If you want to load code in the middle of the program, that's tricky too. I don't think anyone's made a dlopen/ClassLoader sort of thing for loading rust code.

But it is possible to use --crate-type=cdylib, and then mark some functions as

#[no_mangle]
pub extern "C" fn my_fn() {
}

this causes Rust to build a C-style dynamic library. And extern "C" functions with #[no_mangle] can be loaded from the library. A crate like dlopen or libloading can dynamically load the cdylib.

I made a proof-of-concept for an internet simulator that uses this. It uses the dlopen crate. My idea was that users could create node plugins that the main code could use. It worked as intended! But there might have been some safety issue I missed.
Loading code
Plugin code

3 Likes

Yeah the safe issue is a bit new to me in this respect.
I mean could you write the bulk of the code to be safe with the exception of the dynamic linking part?

The idea would be to have some sort of stub that does a bunch of common code but then depending on user input of in response to an event, dynamic loading of code occurs where your loading the code based on some sort of URL

Its been over a decade since I last looked at this.
Just trying to see what could be done…

Thx.

You can, as long as you are not trying to unload the dylib. (Unloading is a can of worms)

1 Like

Yeah, thought about that…

No other language seems to handle unloading…

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.