Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Rust have a dlopen equivalent

Tags:

plugins

rust

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?

like image 857
Matt Avatar asked Mar 17 '14 17:03

Matt


3 Answers

The Rust FAQ officially endorses libloading. Beyond that, there are three different options I know of:

  • Use the shared_library crate
  • Use the dylib crate.
  • Use 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.

like image 195
Per Lundberg Avatar answered Nov 14 '22 13:11

Per Lundberg


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();
}
like image 21
Alexander Samoilov Avatar answered Nov 14 '22 14:11

Alexander Samoilov


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).

like image 22
Lily Ballard Avatar answered Nov 14 '22 13:11

Lily Ballard