Skip to content

Commit 13e0f72

Browse files
committed
explain how to turn integers into fn ptrs
(with an intermediate raw ptr, not a direct transmute)
1 parent 04099e3 commit 13e0f72

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

core/src/intrinsics.rs

+3
Original file line numberDiff line numberDiff line change
@@ -930,6 +930,9 @@ extern "rust-intrinsic" {
930930
/// fn foo() -> i32 {
931931
/// 0
932932
/// }
933+
/// // Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
934+
/// // This avoids an integer-to-pointer `transmute`, which can be problematic.
935+
/// // Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
933936
/// let pointer = foo as *const ();
934937
/// let function = unsafe {
935938
/// std::mem::transmute::<*const (), fn() -> i32>(pointer)

core/src/primitive_docs.rs

+26
Original file line numberDiff line numberDiff line change
@@ -1338,6 +1338,32 @@ mod prim_ref {}
13381338
/// is a reference to the function-specific ZST. `&bar` is basically never what you
13391339
/// want when `bar` is a function.
13401340
///
1341+
/// ### Casting to and from integers
1342+
///
1343+
/// You cast function pointers directly to integers:
1344+
///
1345+
/// ```rust
1346+
/// let fnptr: fn(i32) -> i32 = |x| x+2;
1347+
/// let fnptr_addr = fnptr as usize;
1348+
/// ```
1349+
///
1350+
/// However, a direct cast back is not possible. You need to use `transmute`:
1351+
///
1352+
/// ```rust
1353+
/// # let fnptr: fn(i32) -> i32 = |x| x+2;
1354+
/// # let fnptr_addr = fnptr as usize;
1355+
/// let fnptr = fnptr_addr as *const ();
1356+
/// let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
1357+
/// assert_eq!(fnptr(40), 42);
1358+
/// ```
1359+
///
1360+
/// Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
1361+
/// This avoids an integer-to-pointer `transmute`, which can be problematic.
1362+
/// Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
1363+
///
1364+
/// Note that all of this is not portable to platforms where function pointers and data pointers
1365+
/// have different sizes.
1366+
///
13411367
/// ### Traits
13421368
///
13431369
/// Function pointers implement the following traits:

0 commit comments

Comments
 (0)