CString::new().unwrap().as_ptr() 给出空 *const c_char

CString::new().unwrap().as_ptr() gives empty *const c_char

我有一个需要 *const std::os::raw::c_char 的 C 函数,我在 Rust 中完成了以下操作:

use std::os::raw::c_char;
use std::ffi::{CString, CStr};
extern crate libc;

fn main() {
    let _test_str: *const c_char = CString::new("Hello World").unwrap().as_ptr();
    let fmt: *const c_char = CString::new("%s\n").unwrap().as_ptr();
    unsafe { libc::printf(fmt, _test_str); }

    unsafe {
        let slice = CStr::from_ptr(_test_str);
        println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
    }
}

但是,我无法_test_str打印出来,上面程序的输出只是

string buffer size without nul terminator: 0

如果我将 _test_str 传递给某个 C 函数并看到它是一个空字符串。我做错了什么?

您正在创建 CString 与创建指向它的指针相同的语句。 CString 被拥有但未绑定到变量,因此它仅与封闭语句一样存在,导致指针无效。 documentation for as_ptr:

特别警告

For example, the following code will cause undefined behavior when ptr is used inside the unsafe block:

use std::ffi::{CString};

let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
unsafe {
    // `ptr` is dangling
    *ptr;
}

This happens because the pointer returned by as_ptr does not carry any lifetime information and the CString is deallocated immediately after the CString::new("Hello").expect("CString::new failed").as_ptr() expression is evaluated.

您可以通过引入对整个函数都有效的变量来解决这个问题,然后创建指向这些变量的指针:

fn main() {
    let owned_test = CString::new("Hello World").unwrap();
    let _test_str: *const c_char = owned_test.as_ptr();
    let owned_fmt = CString::new("%s\n").unwrap();
    let fmt: *const c_char = owned_fmt.as_ptr();

    unsafe {
        libc::printf(fmt, _test_str);
    }

    unsafe {
        let slice = CStr::from_ptr(_test_str);
        println!(
            "string buffer size without nul terminator: {}",
            slice.to_bytes().len()
        );
    }

    // owned_fmt is dropped here, making fmt invalid
    // owned_test is dropped here, making _test_str invalid
}

如果您使用原始指针,则需要格外小心,确保它们始终指向实时数据。引入变量是准确控制数据生存时间的最佳方式 - 它将从变量初始化到变量超出范围的那一刻存在。