rust ffi数据之间相互转换

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>()) };

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 wind.kaisa@gmail.com

文章标题:rust ffi数据之间相互转换

本文作者:kaisawind

发布时间:2020-05-25, 07:28:42

最后更新:2020-12-01, 10:28:14

原始链接:https://kaisawind.gitee.io/2020/05/24/2020-05-25-rust-ffi/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏