2 个版本
0.1.1 | 2021年9月24日 |
---|---|
0.1.0 | 2021年9月23日 |
#28 in #pointer
每月58次下载
在 2 个crate中使用 (通过 gmod)
5KB
✨ null_fn
一个过程属性宏,允许在 static
中创建空函数指针。
此crate是 不安全的并且容易导致UB,Option<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