Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/williamvenner/null_fn
✨ A proc attribute macro that allows for creating null function pointers in statics
https://github.com/williamvenner/null_fn
ffi fn function macro null pointer pointers proc-macro proc-macro-attributes ptr rust unsafe
Last synced: 26 days ago
JSON representation
✨ A proc attribute macro that allows for creating null function pointers in statics
- Host: GitHub
- URL: https://github.com/williamvenner/null_fn
- Owner: WilliamVenner
- License: mit
- Created: 2021-09-23T23:07:00.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2021-09-24T00:31:02.000Z (about 3 years ago)
- Last Synced: 2024-10-11T11:33:28.129Z (about 1 month ago)
- Topics: ffi, fn, function, macro, null, pointer, pointers, proc-macro, proc-macro-attributes, ptr, rust, unsafe
- Language: Rust
- Homepage: https://crates.io/crates/null_fn
- Size: 4.88 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[![crates.io](https://img.shields.io/crates/v/null_fn.svg)](https://crates.io/crates/null_fn)
# ✨ `null_fn`
A proc attribute macro that allows for creating null function pointers in `static`s.
This crate is **unsafe and easy to cause UB with**, `Option` is [FFI safe](https://doc.rust-lang.org/nomicon/ffi.html#the-nullable-pointer-optimization) and may be a more appropriate alternative if you value type safety.
## Example
```rust
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-optimizationlet 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! */
}
}
```