dlopen2/symbor/
symbol.rs

1use super::super::err::Error;
2use super::from_raw::{FromRawResult, RawResult};
3use std::marker::PhantomData;
4use std::mem::transmute_copy;
5use std::ops::{Deref, DerefMut};
6
7/// Safe wrapper around a symbol obtained from `Library`.
8///
9/// This is the most generic type, valid for obtaining functions, references and pointers.
10/// It does not accept null value of the library symbol. Other types may provide
11/// more specialized functionality better for some use cases.
12#[derive(Debug, Clone, Copy)]
13pub struct Symbol<'lib, T: 'lib> {
14    symbol: T,
15    pd: PhantomData<&'lib T>,
16}
17
18impl<'lib, T> Symbol<'lib, T> {
19    pub fn new(symbol: T) -> Symbol<'lib, T> {
20        Symbol {
21            symbol,
22            pd: PhantomData,
23        }
24    }
25}
26
27impl<'lib, T> FromRawResult for Symbol<'lib, T> {
28    unsafe fn from_raw_result(raw_result: RawResult) -> Result<Self, Error> {
29        match raw_result {
30            Ok(ptr) => {
31                if ptr.is_null() {
32                    Err(Error::NullSymbol)
33                } else {
34                    let raw: *const () = *ptr;
35                    Ok(Symbol {
36                        symbol: transmute_copy(&raw),
37                        pd: PhantomData,
38                    })
39                }
40            }
41            Err(err) => Err(err),
42        }
43    }
44}
45
46impl<'lib, T> Deref for Symbol<'lib, T> {
47    type Target = T;
48    fn deref(&self) -> &T {
49        &self.symbol
50    }
51}
52
53impl<'lib, T> DerefMut for Symbol<'lib, T> {
54    //type Target =  T;
55    fn deref_mut(&mut self) -> &mut T {
56        &mut self.symbol
57    }
58}
59
60unsafe impl<'lib, T: Send> Send for Symbol<'lib, T> {}
61unsafe impl<'lib, T: Sync> Sync for Symbol<'lib, T> {}