Rust. I have: const DEVICEEXTENSIONS: &'static [&'static str] = &["VKKHR_swapchain"];…
- User
Rust. I have: const DEVICE_EXTENSIONS: &'static [&'static str] = &["VK_KHR_swapchain"];
How do I convert it to [*const c_char]
- Assistant
To convert a Rust slice of string literals to a slice of raw pointers to null-terminated C strings (
[*const c_char]), you need to follow these steps:- Import necessary modules.
- Create a vector to hold the raw pointers.
- Convert each string literal to a C-compatible string and get a raw pointer to it.
- User
How do I print the raw_poitners_slice
- Assistant
To print the contents of
raw_pointers_slice, you need to follow these steps:- Iterate over the slice.
- Convert each raw pointer back to a
&CStrto safely convert it to a Rust string for printing. - Print the strings.
Below is the updated code which includes printing the contents of
raw_pointers_slice:use std::ffi::{CStr, CString}; use std::os::raw::c_char; fn main() { const DEVICE_EXTENSIONS: &'static [&'static str] = &["VK_KHR_swapchain"]; // Convert each &str to a CString and then into a *const c_char let cstrings: Vec<_> = DEVICE_EXTENSIONS .iter() .map(|&s| CString::new(s).expect("Failed to create CString")) .collect(); // Convert each CString to a raw pointer *const c_char let raw_pointers: Vec<*const c_char> = cstrings .iter() .map(|cs| cs.as_ptr()) .collect(); // If you need a pointer to the array you can store it in a variable let raw_pointers_slice: &[*const c_char] = &raw_pointers; // Now `raw_pointers_slice` is of type &[*const c_char] // Iterate over the slice and print each string for &ptr in raw_pointers_slice.iter() { let c_str = unsafe { CStr::from_ptr(ptr) }; let str_slice = c_str.to_str().expect("CStr::to_str failed"); println!("{}", str_slice); } } - User
Implement: fn str_to_c_chars(s: Vec<&str>) -> Box<[*const c_char]> {
- Assistant