Does Rust have a dlopen equivalent

后端 未结 3 970
梦如初夏
梦如初夏 2020-12-08 07:14

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?

相关标签:
3条回答
  • 2020-12-08 08:00

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 08:18

    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();
    }
    
    0 讨论(0)
提交回复
热议问题