Why would it be necessary to perform two casts to a mutable raw pointer in a row?

后端 未结 1 804
臣服心动
臣服心动 2021-01-11 16:58

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         


        
相关标签:
1条回答
  • 2021-01-11 17:23

    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
    

    The timeout in that file is defined as:

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

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

    &mut timeout as *mut _ as *mut _
    

    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.

    0 讨论(0)
提交回复
热议问题