fn-ptr
This is a small utility crate that provides the FnPtr trait, which is implemented for all function pointer types:
fn(T) -> Uunsafe fn(T) -> Uextern "C" fn(T)unsafe extern "sysv64" fn() -> i32
The trait provides associated types and constants to introspect function pointer types at compile time.
Features
1. Function Pointer Metadata
Every function pointer automatically implements FnPtr.
Depending on the type, they also implement SafeFnPtr,, UnsafeFnPtr, and HasAbi<Abi>.
With it you can inspect the type of function:
use ;
type F = extern "C" fn ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
There are also some const helper functons to do so ergonomically.
const A: usize = ; // 2
const SAFE: bool = ; // true
const EXT: bool = ; // true
const ABI: Abi = ; // Abi::C
2. Toggle Function Pointer Safety
You can toggle the safety of a function pointer at the type level:
use ;
type U = unsafe extern "C" fn;
type S = make_safe!; // extern "C" fn(i32)
type S2 = extern "C" fn;
type U2 = make_unsafe!; // unsafe extern "C" fn(i32)
Or at the instance level:
let safe_add: fn = ;
let unsafe_add: unsafe fn = safe_add.as_unsafe;
let safe_add2: fn = unsafe ;
3. Changing ABIs
You can also change the ABI of a function pointer at the type level:
use ;
type F = extern "C" fn ;
type G = with_abi!;
type H = with_abi!;
Or at the instance level:
use ;
let rust_add: fn = ;
// Safety: not actually safe!
let c_add: extern "C" fn = unsafe > };
Note that this does not change the underlying ABI and should be used with caution.
How It Works
To implement the traits for all function pointer types, there is a large macro.
For the conversion macros the crate relies on two traits: WithAbi and WithSafety that can also be used directly:
use ;
type F = extern "C" fn;
type G = >>F;
type U = >>F;
License
Licensed under the MIT license, see LICENSE for details.