简体   繁体   English

什么是transmute::&lt;*mut c_void, Option<unsafe extern "C" fn() -> ()&gt;&gt;是什么意思?

[英]What does transmute::<*mut c_void, Option<unsafe extern "C" fn() -> ()>> mean?

Here's some code I generated using c2rust and then cleaned up a bit:这是我使用c2rust生成的一些代码,然后进行了一些清理:

#![feature(libc)]
extern crate libc;

use libc::*;
use std::mem::transmute;

extern "C" {
    #[no_mangle]
    fn read(__fd: c_int, __buf: *mut c_void, __nbytes: c_ulong) -> c_long;
    #[no_mangle]
    fn mmap(
        __addr: *mut c_void,
        __len: c_ulong,
        __prot: c_int,
        __flags: c_int,
        __fd: c_int,
        __offset: c_long,
    ) -> *mut c_void;
}

pub fn main() {
    unsafe {
        let buf: *mut c_void = mmap(
            0 as *mut c_void,
            256i32 as c_ulong,
            0x1i32 | 0x2i32 | 0x4i32,
            0x2i32 | 0x20i32,
            -1i32,
            0i32 as c_long,
        );
        read(0i32, buf, 256i32 as c_ulong);
        transmute::<*mut c_void, Option<unsafe extern "C" fn() -> ()>>(buf).unwrap()();
    }
}

While I understand what it does, I'm not sure how to interpret the last expression.虽然我明白它的作用,但我不确定如何解释最后一个表达式。 What does Option<unsafe extern "C" fn() -> ()> mean? Option<unsafe extern "C" fn() -> ()>是什么意思?

We're trying to call an unsafe extern "C" fn() -> () , which is basically a function with no arguments and no return type.我们试图调用一个unsafe extern "C" fn() -> () ,它基本上是一个没有参数和返回类型的函数。 My first attempt was to just use the as keyword, as defined in transmute 's documentation.我的第一次尝试是只使用as关键字,如transmute的文档中所定义。 I got the following error:我收到以下错误:

error[E0605]: non-primitive cast: `*mut libc::c_void` as `unsafe extern "C" fn()`
  --> wx.rs:32:9
   |
32 |         (buf as unsafe extern "C" fn() -> ())();
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

It looks like the function is a non-primitive type and this is why I need transmute .看起来该函数是非原始类型,这就是我需要transmute I tried the following:我尝试了以下方法:

transmute::<
    *mut c_void,
    unsafe extern "C" fn() -> ()
>(buf)();

And the code compiled and actually ran as expected.并且代码编译并实际按预期运行。

What I still don't understand is why Option was used by c2rust, but the code works fine without it.我仍然不明白的是为什么Option了使用c2rust,但代码工作正常,没有它。 It appears that unsafe and extern "C" can also be dropped and the code still works, at least for me.似乎unsafeextern "C"也可以删除,代码仍然有效,至少对我来说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM