I'm looking at converted some C++ code to Rust. It needs to use a combination of CreateFileMappingW and MapViewOfFile to access a shared memory segment using the Microsoft Windows API bindings.
From C/C++ MapViewOfFile normally returns a pointer to the memory segment mapped into the process. You can dereference it and change it etc.
From Rust its returning a Result<MEMORYMAPPEDVIEW_HANDLE, Error>
so as a first cut, I have code like the following just to see if the expected values are in there.
if let Ok(pBuf) = unsafe { MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 1024) } {
let p = pBuf.0;
let ptr: *const u8 = p as *const u8;
let slice = unsafe { std::slice::from_raw_parts(ptr, 10) };
println!("ptr: {:?}", slice);
println!("Mapped view of file {:?}", pBuf.0);
} else {
println!("Failed to map view of file");
unsafe {
CloseHandle(hMapFile);
}
}
which they are not!
My question is, is this the correct method of accessing a raw pointer? My second question is, is it possible to cast that pointer to a C-style layout struct so I can access the underlying fields directly?