rust - 从固定大小的 c_char 数组转换为 CString

标签 rust ffi

我的 FFI 绑定(bind)返回一个具有固定大小 c_char 数组的结构,我想将它们转换为 std::ffi::CStringstd::字符串

看起来 CString::new 函数将指针强制转换为向量。

use std::ffi::CString;
use std::os::raw::c_char;

#[repr(C)]
pub struct FFIStruct {
    pub Id: [::std::os::raw::c_char; 256usize],
    pub Description: [::std::os::raw::c_char; 256usize],
}

fn get_struct() -> Option<FFIStruct> {
    println!("cheating");
    None
}

pub fn main() {
    match get_struct() {
        Some(thing) => 
            println!("Got id:{}",CString::new(thing.Id.as_ptr())),

        None => (),
    }
}

这是 Rust Playground链接。

最佳答案

您不拥有的 C 字符串应该使用 CStr 进行翻译,而不是 CString。然后,您可以将其转换为拥有的表示形式 (CString) 或将其转换为 String:

extern crate libc;

use libc::c_char;
use std::ffi::CStr;

pub fn main() {
    let id = [0 as c_char; 256];
    let rust_id = unsafe { CStr::from_ptr(id.as_ptr()) };
    let rust_id = rust_id.to_owned();
    println!("{:?}", rust_id);
}

您还应该为 c_char 等类型使用 libc 包。

关于rust - 从固定大小的 c_char 数组转换为 CString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37421392/

相关文章:

lua - 如何将 cdata 结构转换为 lua 字符串?

javascript - 模块名称是绑定(bind)中使用的隐藏全局名称

rust - 在 C 管理的内存中正确存储 Rust Rc<T>

c - 将 Rust 特性传递给 C

haskell - 将 OCaml 代码与共享库链接

arrays - 切片与数组的比较在 Rust 中如何工作?

regex - Rust程序中的正则表达式

ffi - 在 FFI 中使用 c_void

rust - 是否可以专注于静态生命周期?

rust - 使用 bindgen 设置包含路径