File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff 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:
You can’t perform that action at this time.
0 commit comments