为什么必须连续对可变的原始指针执行两次强制转换? [英] Why would it be necessary to perform two casts to a mutable raw pointer in a row?

查看:99
本文介绍了为什么必须连续对可变的原始指针执行两次强制转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看 unix-socket ,我遇到了以下代码:

When looking at unix-socket, I came across this code:

let timeout = unsafe {
    let mut timeout: libc::timeval = mem::zeroed();
    let mut size = mem::size_of::<libc::timeval>() as libc::socklen_t;
    try!(cvt(libc::getsockopt(self.0,
                              libc::SOL_SOCKET,
                              kind,
                              &mut timeout as *mut _ as *mut _,
                              &mut size as *mut _ as *mut _)));
    timeout
};

我特别对这些行感到好奇:

I was curious about these lines in particular:

&mut timeout as *mut _ as *mut _,
&mut size as *mut _ as *mut _

为什么必须连续对可变的原始指针执行两次强制转换?为什么只铸一次就不够了?

Why is it necessary to perform two casts to a mutable raw pointer in a row? Why wouldn't it have been sufficient to only cast once?

推荐答案

例如timeout对应于

The timeout for example corresponds to a *mut c_void parameter:

pub unsafe extern fn getsockopt(sockfd: c_int, level: c_int, optname: c_int,
                                optval: *mut c_void, optlen: *mut socklen_t) -> c_int

该文件中的timeout定义为:

let mut timeout: libc::timeval = mem::zeroed();

所以它的类型是libc::timeval.现在让我们考虑:

So it's of type libc::timeval. Now let's consider:

&mut timeout as *mut _ as *mut _

首先您拥有&mut timeout,所以它的类型为&mut libc::timeval.然后,您执行as *mut _将其强制为推断类型的原始可变指针,在这种情况下,该指针与libc::timeval的类型相同,因此到目前为止的完整类型为:*mut libc::timeval,与参数类型*mut c_void.最终的as *mut _再次推断目标类型,现在是参数类型*mut c_void,因此最终将*mut libc::timeval强制为*mut c_void.

First you have &mut timeout so that is of type &mut libc::timeval. Then you do as *mut _ to coerce it to a raw mutable pointer of an inferred type, which in this case is the same type of libc::timeval, so the full type so far is: *mut libc::timeval, which doesn't match the parameter type *mut c_void. The final as *mut _ again infers the target type, which is now the parameter type *mut c_void, so this finally coerces the *mut libc::timeval to a *mut c_void.

这篇关于为什么必须连续对可变的原始指针执行两次强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆