本文簡要介紹rust語言中 std::ffi::CStr.as_ptr
的用法。
用法
pub const fn as_ptr(&self) -> *const c_char
返回指向此 C 字符串的內部指針。
返回的指針將在 self
有效的時間內有效,並指向以 0 字節終止的連續內存區域,以表示字符串的結尾。
WARNING
返回的指針是隻讀的;寫入它(包括將它傳遞給寫入它的 C 代碼)會導致未定義的行為。
您有責任確保不會過早釋放底層內存。例如,當 ptr
在 unsafe
塊內使用時,以下代碼將導致未定義的行為:
use std::ffi::CString;
let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
unsafe {
// `ptr` is dangling
*ptr;
}
發生這種情況是因為 as_ptr
返回的指針不攜帶任何生命周期信息,並且在計算 CString::new("Hello").expect("CString::new failed").as_ptr()
表達式後立即釋放 CString
。要解決此問題,請將 CString
綁定到局部變量:
use std::ffi::CString;
let hello = CString::new("Hello").expect("CString::new failed");
let ptr = hello.as_ptr();
unsafe {
// `ptr` is valid because `hello` is in scope
*ptr;
}
這樣,hello
中 CString
的生命周期就包含了ptr
和unsafe
塊的生命周期。
相關用法
- Rust CStr.into_c_string用法及代碼示例
- Rust CStr.from_bytes_with_nul用法及代碼示例
- Rust CStr.from_bytes_with_nul_unchecked用法及代碼示例
- Rust CStr.from_ptr用法及代碼示例
- Rust CStr.to_bytes用法及代碼示例
- Rust CStr.to_str用法及代碼示例
- Rust CStr.to_string_lossy用法及代碼示例
- Rust CStr.to_bytes_with_nul用法及代碼示例
- Rust CString.into_bytes用法及代碼示例
- Rust CString.from_raw用法及代碼示例
- Rust CString.into_boxed_c_str用法及代碼示例
- Rust CStr用法及代碼示例
- Rust CString.into_raw用法及代碼示例
- Rust CString.as_c_str用法及代碼示例
- Rust CString.from_vec_unchecked用法及代碼示例
- Rust CString.from_vec_with_nul_unchecked用法及代碼示例
- Rust CString.from_vec_with_nul用法及代碼示例
- Rust CString.as_bytes用法及代碼示例
- Rust CString用法及代碼示例
- Rust CString.into_bytes_with_nul用法及代碼示例
- Rust CString.as_bytes_with_nul用法及代碼示例
- Rust CString.new用法及代碼示例
- Rust CString.into_string用法及代碼示例
- Rust Cursor.new用法及代碼示例
- Rust Condvar.notify_all用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::ffi::CStr.as_ptr。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。