Does Rust have a way to make a program pluggable. In C the plugins I create are .so files that I load with dlopen. Does Rust provide a native way of doing the same thing?
The Rust FAQ officially endorses libloading. Beyond that, there are three different options I know of:
std::dynamic_lib
, which is deprecated since Rust 1.5. (These docs are no longer available in version 1.32; it's likely the feature has been dropped altogether by now.)I haven't tried any of these, so I cannot really say which is best or what the pros/cons are for the different variants. I'd strongly advise against using std::dynamic_lib
at least, given that it's deprecated and will likely be made private at some point in the future.
Exactly,
And below is the complete use case example:
use std::unstable::dynamic_lib::DynamicLibrary;
use std::os;
fn load_cuda_library()
{
let path = Path::new("/usr/lib/libcuda.so");
// Make sure the path contains a / or the linker will search for it.
let path = os::make_absolute(&path);
let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
Err(error) => fail!("Could not load the library: {}", error)
};
// load cuinit symbol
let cuInit: extern fn(u32) -> u32 = unsafe {
match lib.symbol("cuInit") {
Err(error) => fail!("Could not load function cuInit: {}", error),
Ok(cuInit) => cuInit
}
};
let argument = 0;
let expected_result = 0;
let result = cuInit(argument);
if result != expected_result {
fail!("cuInit({:?}) != {:?} but equaled {:?}",
argument, expected_result, result)
}
}
fn main()
{
load_cuda_library();
}
Yes. There's a module std::unstable::dynamic_lib
that enables dynamic loading of libraries. It's undocumented, though, as it's a highly experimental API (everything in std::unstable
is undocumented). As @dbaupp suggests, the source is the best documentation (current version is af9368452).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With