0

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?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • I'm not sure you can use memory-mapped files from Rust in general. Access failures are reported as [SEH](https://learn.microsoft.com/en-us/windows/win32/debug/structured-exception-handling) exceptions, something Rust has no support for (to my knowledge). – IInspectable May 23 '23 at 12:28
  • Interesting. Will look into that some more although I did just get them working (silly mistake in the name) and I also answered my own question around overlaying a struct on a ptr. along the lines of ``` #[repr(C, packed)] struct MyPayload { some_field: c_int, } let payload = p as *mut MyPayload; ``` – waistcoat1971 May 23 '23 at 12:45
  • The pointer gymnastics smell like UB. Since this snippet doesn't actually "overlay" a structure onto memory, but rather makes a copy you could consider calling [`read_unaligned`](https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html) instead. As always with `unsafe` Rust, make sure to study [The Rustonomicon](https://doc.rust-lang.org/nomicon/). Also relevant: [C Is Not a Low-level Language](https://queue.acm.org/detail.cfm?id=3212479), which pretty much all-around applies to Rust just the same. – IInspectable May 27 '23 at 09:03

0 Answers0