不幸的是,Rust没有对VLA提供直接支持.因此,您需要手动完成这项工作(不比C语言差,但在C语言中,您可以使用大多数语言的工具来处理指针,而在Rust中,您必须使用原始指针,不能使用引用).您还需要非常小心,不要创建引用,因为references can only be used to read the data within the size of the type they are pointing to.您也不能创建对未初始化内存的引用.
下面是这样做的一个例子:
unsafe {
// Allocate space for 2 elements (one is already there).
let layout = std::alloc::Layout::new::<tagLOGPALETTE>()
.extend(std::alloc::Layout::array::<tagPALETTEENTRY>(1).unwrap())
.unwrap()
.0;
let log_pal = std::alloc::alloc(layout).cast::<tagLOGPALETTE>();
if log_pal.is_null() {
std::alloc::handle_alloc_error(layout);
}
// Don't use `*` or `=`, it will create a reference!
std::ptr::addr_of_mut!((*log_pal).palNumEntries).write(2);
let entry = std::mem::zeroed::<tagPALETTEENTRY>();
std::ptr::addr_of_mut!((*log_pal).palPalEntry[0])
.add(0)
.write(entry);
std::ptr::addr_of_mut!((*log_pal).palPalEntry[0])
.add(1)
.write(entry);
// Here, after you initialized them, you can create a slice of the entries:
let entries = std::slice::from_raw_parts(std::ptr::addr_of!((*log_pal).palPalEntry[0]), 2);
// But you can't create a reference to the whole type, even without accessing the entires
// (only other fields), because you didn't initialize `palVersion`!
}