Struct detour::StaticDetour[][src]

pub struct StaticDetour<T: Function> { /* fields omitted */ }
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

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()? };

Enables the detour.

Disables the detour.

Returns whether the detour is enabled or not.

Changes the detour, regardless of whether the hook is enabled or not.

Trait Implementations

Executes the destructor for this type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.