Buffer example should be unsafe
use bindings::{Windows::Foundation::*, Windows::Win32::System::WinRT::IMemoryBufferByteAccess};
use windows::*;
-fn as_slice(buffer: &IMemoryBufferReference) -> Result<&mut [u8]> {
+// This example illustrates how to use IMemoryBufferByteAccess to access the underlying buffer
+// owned by the MemoryBuffer/IMemoryBufferReference. Note that this is inherently unsafe as
+// this function does not perform borrow/lifetime checking. The caller must ensure that the
+// IMemoryBufferReference remains alive and that that buffer is not shared across threads.
+
+unsafe fn as_mut_slice(buffer: &IMemoryBufferReference) -> Result<&mut [u8]> {
let interop = buffer.cast::<IMemoryBufferByteAccess>()?;
let mut data = std::ptr::null_mut();
let mut len = 0;
- unsafe {
interop.GetBuffer(&mut data, &mut len).ok()?;
Ok(std::slice::from_raw_parts_mut(data, len as _))
}
-}
fn main() -> Result<()> {
let buffer = MemoryBuffer::Create(11)?;
@@ -19,13 +22,13 @@ fn main() -> Result<()> {
// Write to buffer...
{
- let slice = as_slice(&reference)?;
+ let slice = unsafe { as_mut_slice(&reference)? };
slice.copy_from_slice(b"hello world");
}
// Read from buffer...
{
- let slice = as_slice(&reference)?;
+ let slice = unsafe { as_mut_slice(&reference)? };
assert_eq!(slice, b"hello world");
}
