سؤال

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:

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top