Raw pointer turns null passing from Rust to C

前端 未结 1 1411
挽巷
挽巷 2020-12-11 20:34

I\'m attempting to retrieve a raw pointer from on C function in rust, and use that same raw pointer as an argument in another C function from another library. When I pass th

1条回答
  •  执念已碎
    2020-12-11 20:55

    CString::new("…").unwrap().as_ptr() does not work. The CString is temporary, hence the as_ptr() call returns the inner pointer of that temporary, which will likely be dangling when you use it. This is “safe” per Rust's definition of safety as long as you don't use the pointer, but you eventually do so in a unsafe block. You should bind the string to a variable and use as_ptr on that variable.

    This is such a common problem, there is even a proposal to fix the CStr{,ing} API to avoid it.

    Additionally raw pointer are nullable by themselves, so the Rust FFI equivalent of const struct rte_eth_rxconf * would be *const ffi::RteEthRxConf, not Option<*const ffi::RteEthRxConf>.

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