Struct detour::StaticDetour
source · [−]pub struct StaticDetour<T: Function> { /* private fields */ }
Expand description
A type-safe static detour.
Due to being generated by a macro, the StaticDetour::call
method is not
exposed in the documentation.
/// Calls the original function regardless of whether it's hooked or not.
///
/// Panics if called when the static detour has not yet been initialized.
fn call(&self, T::Arguments) -> T::Output
To define a static detour, use the static_detour macro.
Example
use std::error::Error;
use detour::static_detour;
static_detour! {
static Test: fn(i32) -> i32;
}
fn add5(val: i32) -> i32 {
val + 5
}
fn add10(val: i32) -> i32 {
val + 10
}
fn main() -> Result<(), Box<dyn Error>> {
// Replace the 'add5' function with 'add10' (can also be a closure)
unsafe { Test.initialize(add5, add10)? };
assert_eq!(add5(1), 6);
assert_eq!(Test.call(1), 6);
unsafe { Test.enable()? };
// The original function is detoured to 'add10'
assert_eq!(add5(1), 11);
// The original function can still be invoked using 'call'
assert_eq!(Test.call(1), 6);
// It is also possible to change the detour whilst hooked
Test.set_detour(|val| val - 5);
assert_eq!(add5(5), 0);
unsafe { Test.disable()? };
assert_eq!(add5(1), 6);
Ok(())
}
Implementations
sourceimpl<T: Function> StaticDetour<T>
impl<T: Function> StaticDetour<T>
sourcepub unsafe fn initialize<D>(&self, target: T, closure: D) -> Result<&Self>where
D: Fn<T::Arguments, Output = T::Output> + Send + 'static,
pub unsafe fn initialize<D>(&self, target: T, closure: D) -> Result<&Self>where
D: Fn<T::Arguments, Output = T::Output> + Send + 'static,
Create a new hook given a target function and a compatible detour closure.
This method can only be called once per static instance. Multiple calls
will error with AlreadyExisting
.
It returns &self
to allow chaining initialization and activation:
unsafe { Test.initialize(add5, |x| x - 5)?.enable()? };
sourcepub fn is_enabled(&self) -> bool
pub fn is_enabled(&self) -> bool
Returns whether the detour is enabled or not.
Trait Implementations
Auto Trait Implementations
impl<T> RefUnwindSafe for StaticDetour<T>where
T: RefUnwindSafe,
impl<T> Send for StaticDetour<T>where
T: Send,
impl<T> Sync for StaticDetour<T>
impl<T> Unpin for StaticDetour<T>where
T: Unpin,
impl<T> !UnwindSafe for StaticDetour<T>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more