rust ffi数据之间相互转换 - Mon, May 25, 2020
rust ffi数据之间相互转换
1. 字符串之间转换
1.1. String->*const c_char
CString
表示字符串来自rust要转成c.
String -> CString -> *const c_char
let svcname: *const ::std::os::raw::c_char;
let name = ::std::ffi::CString::new("device-random").expect("CString::new failed");
svcname = name.as_ptr();
1.2. *const c_char -> String
CStr
表示字符串来自c要转成rust.
*const c_char -> CStr -> String
let name = unsafe {::std::ffi::CStr::from_ptr(svcname)};
let name = name.to_str().unwrap();
1.3. String -> * c_char
接上
String -> CString -> * c_char
let svcname: *mut ::std::os::raw::c_char;
let name = ::std::ffi::CString::new(name).unwrap().into_raw();
svcname = name;
1.4. Args -> *mut *mut ::std::os::raw::c_char
程序参数转换
let argv: *mut *mut ::std::os::raw::c_char;
let mut args = env::args()
.map(|arg| CString::new(arg).unwrap().into_raw())
.collect::<Vec<*mut c_char>>();
argv = args.as_mut_ptr();
2. 数组之间转换
2.1. 结构体数组取第i
个数据
let requests: *const edgex_device_commandrequest;
let request = *requests.offset(i as isize);
2.2. 结构体数组转换
let readings: &mut [devsdk_commandresult] = slice::from_raw_parts_mut(
readings,
nreadings as usize * mem::size_of::<devsdk_commandresult>(),
);
3. 结构体之间转换
3.1. void -> object
let impl_: *mut ::std::os::raw::c_void;
let driver: &mut RandomDriver = &mut *(impl_ as *mut RandomDriver);
3.2. object -> rust
let impl_: *mut ::std::os::raw::c_void = &mut driver as *mut _ as *mut ::std::os::raw::c_void;
3.3 结构体初期化
let driver = unsafe { libc::malloc(std::mem::size_of::<RandomDriver>()) };