Does Rust have a dlopen equivalent

后端 未结 3 972
梦如初夏
梦如初夏 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: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();
    }
    

提交回复
热议问题