【问题标题】:Cast to inferred function type in Rust强制转换为 Rust 中的推断函数类型
【发布时间】:2021-10-01 07:54:50
【问题描述】:

假设我们有一个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 总是返回地址指向被引用函数的函数,而不是指向我们提供的地址的地址。因此,考虑到目前的布局,是否可以从定义中智能地推断出函数类型并将任意类型转换为它?

【问题讨论】:

    标签: generics rust


    【解决方案1】:

    要了解为什么您尝试的解决方案不起作用,我们必须了解 Rust 中不同种类的函数类型;见this answer。当您拨打此电话时:

    let function = cast_to_function(address, &foo);
    

    参数&amp;foo是对具体功能项foo的引用;它不是像address 这样的函数指针。由于cast_to_function() 的类型签名,这意味着返回类型T 是同一个函数项。函数项是零大小的类型,所以cast_to_function() 中的transmute_copy() 没有任何作用。

    最简单的解决方案是在调用cast_to_function()之前将foo转换为函数指针:

    let function = cast_to_function(address, foo as fn(_, _));
    

    (您还需要更改cast_to_function() 的签名以按值获取_fn:_fn: F)。

    这仍然是手动转换的一些样板,但正如演示的那样,您可以使用占位符 (_) 而不是写出每个参数类型。如果参数数量错误,只会出现编译错误(您不能不小心将foo 转换为错误的签名)。


    摆脱调用者代码中所需的强制转换更加复杂。我想出了这个解决方案,它使用一个 trait 来进行转换,并使用一个宏来为不同数量的函数编写 impl:

    /// 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);
    

    无需任何手动转换。

    注意:最后一种解决方案假设函数指针和数据指针大小相同,但在某些平台上可能并非总是如此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多