Crates.io | dlopen2 |
lib.rs | dlopen2 |
version | 0.7.0 |
source | src |
created_at | 2022-07-05 13:43:33.413368 |
updated_at | 2024-02-06 22:17:42.4346 |
description | Library for opening and operating on dynamic link libraries (also known as shared objects or shared libraries). |
homepage | |
repository | https://github.com/OpenByteDev/dlopen2 |
max_upload_size | |
id | 619708 |
size | 116,552 |
This is a fork of the original, now unmaintained dlopen
with updated dependencies, bug fixes and some new features.
This library is my effort to make use of dynamic link libraries in Rust simple. Previously existing solutions were either unsafe, provided huge overhead of required writing too much code to achieve simple things. I hope that this library will help you to quickly get what you need and avoid errors.
use dlopen2::wrapper::{Container, WrapperApi};
#[derive(WrapperApi)]
struct Api<'a> {
example_rust_fun: fn(arg: i32) -> u32,
example_c_fun: unsafe extern "C" fn(),
example_reference: &'a mut i32,
// A function or field may not always exist in the library.
example_c_fun_option: Option<unsafe extern "C" fn()>,
example_reference_option: Option<&'a mut i32>,
}
fn main(){
let mut cont: Container<Api> =
unsafe { Container::load("libexample.so") }.expect("Could not open library or load symbols");
cont.example_rust_fun(5);
unsafe{ cont.example_c_fun() };
*cont.example_reference_mut() = 5;
// Optional functions return Some(result) if the function is present or None if absent.
unsafe{ cont.example_c_fun_option() };
// Optional fields are Some(value) if present and None if absent.
if let Some(example_reference) = &mut cont.example_reference_option {
*example_reference = 5;
}
}
Feature | dlopen2 | libloading | sharedlib |
---|---|---|---|
Basic functionality | Yes | Yes | Yes |
Multiplatform | Yes | Yes | Yes |
Dangling symbol prevention | Yes | Yes | Yes |
Thread safety | Yes | Potential problem with thread-safety of dlerror() on some platforms like FreeBSD |
No support for SetErrorMode (library may block the application on Windows) |
Loading of symbols into structures | Yes | No | No |
Overhead | Minimal | Minimal | Some overhead |
Low-level, unsafe API | Yes | Yes | Yes |
Object-oriented friendly | Yes | No | Yes |
Load from the program itself | Yes | No | No |
Obtaining address information (dladdr) | Yes | Unix only | No |
Please note that while Rust aims at being 100% safe language, it does not yet provide mechanisms that would allow me to create a 100% safe library, so I had to settle on 99%. Also the nature of dynamic link libraries requires casting obtained pointers into types that are defined on the application side. And this cannot be safe. Having said that I still think that this library provides the best approach and greatest safety possible in Rust.
Cargo.toml:
[dependencies]
dlopen2 = "0.6"
This code is licensed under the MIT license.
Special thanks to Simonas Kazlauskas whose libloading became code base for my project.