假设我们有一个类型 FARPROC
我们收到的某些 Win32 操作的结果,例如 GetProcAddress
.它的定义如下:
pub type FARPROC = unsafe extern "system" fn() -> isize;
然后需要将此类型转换为有效的函数类型,以便我们可以调用它。作为开发人员,我们知道函数签名(来自文档),但我们需要将这些知识传递给编译器。一个直接的方法是使用 transmute
显式函数类型如下:let address: FARPROC = unsafe { GetProcAddress(module, proc).unwrap() };
let function: extern "system" fn(i32) = unsafe { transmute (&address) };
但是如果我们想从我们在 Rust 代码中定义的现有函数之一推断函数类型怎么办?假设我们有一些定义很长的函数:pub fn foo(arg1: i32, arg2: c_void, arg3: *const c_char) {
// snip
}
为了保持我们的代码 DRY,是否可以在 transmute
中使用该函数类型? ?我尝试的解决方案如下所示:
pub fn cast_to_function<F>(address: FARPROC, _fn: &F) -> F {
unsafe { transmute_copy(&address) }
}
/// Usage
let address: FARPROC = unsafe { GetProcAddress(module, proc).unwrap() };
let function = cast_to_function(address, &foo);
function(1, ...);
此尝试的解决方案基于正在运行的类似 C++ 代码:template<typename T>
T FnCast(void* fnToCast, T pFnCastTo) {
return (T)fnToCast;
}
/// Usage
void bar(int arg1, void* arg2, const char* arg3){
// snip
}
auto address = (void*) GetProcAddress(...);
auto function = FnCast(address, &bar);
function(1, address, "bar");
我在 Rust 中尝试的解决方案的问题是 cast_to_function
总是返回带有指向引用函数的地址的函数,而不是指向我们提供的地址的地址。因此,鉴于到目前为止的布局,是否有可能从函数的定义中智能地推断出函数类型并将任意类型强制转换为它?
最佳答案
要理解为什么您尝试的解决方案不起作用,我们必须了解 Rust 中不同类型的函数类型;见 this answer .当您拨打此电话时:
let function = cast_to_function(address, &foo);
参数 &foo
是对具体功能项foo
的引用;它不是像 address
这样的函数指针.由于 cast_to_function()
的类型签名,这意味着返回类型 T
是同一个功能项。函数项是零大小的类型,所以 transmute_copy()
内cast_to_function()
什么都不做。最简单的解决方案是投
foo
调用前指向函数指针 cast_to_function()
:let function = cast_to_function(address, foo as fn(_, _));
(您还需要更改 cast_to_function()
的签名以取 _fn
的值: _fn: F
)。这仍然是手动转换的一些样板文件,但正如演示的那样,您可以使用占位符(
_
)而不是写出每个参数类型。如果参数数量错误,只会得到编译错误(您不会意外地将 foo
转换为错误的签名)。摆脱调用者代码中所需的强制转换更为复杂。我想出了这个解决方案,它使用 trait 进行转换,并使用宏为不同数量的函数编写实现:
/// Casts a function pointer to a new function pointer, with the new type derived from a
/// template function.
///
/// SAFETY:
/// - `f` must be a function pointer (e.g. `fn(i32) -> i32`)
/// - `template`'s type must be a valid function signature for `f`
unsafe fn fn_ptr_cast<T, U, V>(fn_ptr: T, _template_fn: U) -> V
where
T: Copy + 'static,
U: FnPtrCast<V>,
{
debug_assert_eq!(mem::size_of::<T>(), mem::size_of::<usize>());
U::fn_ptr_cast(fn_ptr)
}
unsafe trait FnPtrCast<U> {
unsafe fn fn_ptr_cast<T>(fn_ptr: T) -> U;
}
macro_rules! impl_fn_cast {
( $($arg:ident),* ) => {
unsafe impl<Fun, Out, $($arg),*> FnPtrCast<fn($($arg),*) -> Out> for Fun
where
Fun: Fn($($arg),*) -> Out,
{
unsafe fn fn_ptr_cast<T>(fn_ptr: T) -> fn($($arg),*) -> Out {
::std::mem::transmute(::std::ptr::read(&fn_ptr as *const T as *const *const T))
}
}
}
}
impl_fn_cast!();
impl_fn_cast!(A);
impl_fn_cast!(A, B);
impl_fn_cast!(A, B, C);
impl_fn_cast!(A, B, C, D);
impl_fn_cast!(A, B, C, D, E);
impl_fn_cast!(A, B, C, D, E, F);
impl_fn_cast!(A, B, C, D, E, F, G);
impl_fn_cast!(A, B, C, D, E, F, G, H);
这让你做let function = fn_ptr_cast(address, foo);
没有任何手动类型转换。注意:最后一个解决方案假设函数指针和数据指针的大小相同,在某些平台上可能并非总是如此。
关于generics - 在 Rust 中转换为推断的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69193944/