File tree 2 files changed +29
-0
lines changed
2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -930,6 +930,9 @@ extern "rust-intrinsic" {
930
930
/// fn foo() -> i32 {
931
931
/// 0
932
932
/// }
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.
933
936
/// let pointer = foo as *const ();
934
937
/// let function = unsafe {
935
938
/// std::mem::transmute::<*const (), fn() -> i32>(pointer)
Original file line number Diff line number Diff line change @@ -1338,6 +1338,32 @@ mod prim_ref {}
1338
1338
/// is a reference to the function-specific ZST. `&bar` is basically never what you
1339
1339
/// want when `bar` is a function.
1340
1340
///
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
+ ///
1341
1367
/// ### Traits
1342
1368
///
1343
1369
/// Function pointers implement the following traits:
You can’t perform that action at this time.
0 commit comments