#pointers #null #static #unsafe

macro null_fn

A proc attribute macro that allows for creating null function pointers in statics

2 releases

0.1.1 Sep 24, 2021
0.1.0 Sep 23, 2021

#26 in #pointer

Download history 16/week @ 2023-12-18 3/week @ 2023-12-25 5/week @ 2024-01-01 45/week @ 2024-01-08 8/week @ 2024-01-15 10/week @ 2024-01-22 261/week @ 2024-01-29 125/week @ 2024-02-05 25/week @ 2024-02-12 174/week @ 2024-02-19 74/week @ 2024-02-26 121/week @ 2024-03-04 48/week @ 2024-03-11 40/week @ 2024-03-18 97/week @ 2024-03-25 114/week @ 2024-04-01

309 downloads per month
Used in 2 crates (via gmod)

MIT license

5KB

crates.io

null_fn

A proc attribute macro that allows for creating null function pointers in statics.

This crate is unsafe and easy to cause UB with, Option<fn()> is FFI safe and may be a more appropriate alternative if you value type safety.

Example

static mut UTIL_PlayerByUserId: unsafe extern "C" fn(userid: i32) -> *mut c_void = unsafe { std::mem::transmute::<*const (), _>(std::ptr::null()) }; // error[E0080]: it is undefined behavior to use this value

#[null_fn]
static mut UTIL_PlayerByUserId: unsafe extern "C" fn(userid: i32) -> *mut c_void = std::ptr::null(); // works!

fn main() {
    unsafe {
        UTIL_PlayerByUserId(20); // This would panic, as we have not initialized the function yet. By default the function is set to a small stub function that panics when called.

        UTIL_PlayerByUserId = /* magically find the pointer to the function; sigscan? */;
		// Setting the function's pointer to a null pointer is UB in Rust.
		// https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization

        let player = UTIL_PlayerByUserId(20); // Now that we set the function pointer, we can call the function without panicking, assuming we found the pointer correctly.

		/* do something with our player! */
    }
}

Dependencies

~1.5MB
~33K SLoC