#pointers #null #static #unsafe

null_fn

一个过程属性宏,允许在静态变量中创建空函数指针

2 个版本

0.1.1 2021年9月24日
0.1.0 2021年9月23日

#28 in #pointer

Download history • Rust 包仓库 114/week @ 2024-04-01 • Rust 包仓库 29/week @ 2024-04-08 • Rust 包仓库 29/week @ 2024-04-15 • Rust 包仓库 28/week @ 2024-04-22 • Rust 包仓库 19/week @ 2024-04-29 • Rust 包仓库 24/week @ 2024-05-06 • Rust 包仓库 29/week @ 2024-05-13 • Rust 包仓库 40/week @ 2024-05-20 • Rust 包仓库 31/week @ 2024-05-27 • Rust 包仓库 23/week @ 2024-06-03 • Rust 包仓库 91/week @ 2024-06-10 • Rust 包仓库 46/week @ 2024-06-17 • Rust 包仓库 23/week @ 2024-06-24 • Rust 包仓库 9/week @ 2024-07-08 • Rust 包仓库 22/week @ 2024-07-15 • Rust 包仓库

每月58次下载
2 个crate中使用 (通过 gmod)

MIT 许可证

5KB

crates.io

null_fn

一个过程属性宏,允许在 static 中创建空函数指针。

此crate是 不安全的并且容易导致UBOption<fn()>FFI安全,并且如果您重视类型安全,可能是一个更合适的替代方案。

示例

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.net.cn/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! */
    }
}

依赖关系

~1.5MB
~35K SLoC