Using Rust to Read a Shared Memory Mapped file created and maintained by another process

382 Views Asked by At

Goal

I'm just beginning in Rust, and wanted to try a small project where I collect some data from the Iracing Simulator. It makes its data and telemetry available via a memory mapped file.

Working example in another language

In Python I can read the file and show that it is accessible using this code:

import mmap

MEMMAPFILE = 'Local\\IRSDKMemMapFileName'
MEMMAPFILESIZE = 1164 * 1024

iracing_data = mmap.mmap(0, MEMMAPFILESIZE, MEMMAPFILE, access=mmap.ACCESS_READ)
print(iracing_data.readline())

And the output looks something like this, which is expected

b'\x02\x00\x00\x00\x01\x00\x00\x00<\x00\x00\x00"\x00\x00\x00\x00\x00\x08\x00p\x00\x00\x005\x01\x00\x00p\x00\x08\x00\x03\x000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x\x00\x00@\x1e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xc2\x01\x00p\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\xc2\x01\x00p`\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00 \xc2\x01\x00p\xc0\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00---\n'

As a starting point I wanted to reproduce this in Rust and proceed from there, but I haven't figured out how to even read the file.

This is in a **Windows **environment (not WSL).

What did I try?

I found the memmap2 crate, but as far as I can tell, it will only produce memory mapped files that can be accessed in the same process. I couldn't find anything in the docs about accessing shared memory and reading existing memory mapped files.

I also found the shared_memory crate, and I tried tweaking an example to read a file, with no success.

fn main() {

    let iracing_file_location = "Local\\IRSDKMemMapFileName";
    
    let iracing_memory = match ShmemConf::new().size(1164 * 1024).flink(iracing_file_location).open() {
        Ok(m) => m,
        Err(ShmemError::LinkExists) => ShmemConf::new().flink(iracing_file_location).open().unwrap(),
        Err(e) => {
            eprintln!("Unable to create or open shmem flink {iracing_file_location} : {e}");
            return;
        }
    };

    let iracing_pointer = iracing_memory.as_ptr();

    unsafe {
        std::ptr::read_volatile(iracing_pointer);
    }
}

Produces:

Unable to create or open shmem flink Local\\\\IRSDKMemMapFileName : Opening the link file failed, The system cannot find the path specified. (os error 3)

I have no doubt I am fundamentally misunderstanding some concepts here, so any help would be appreciated.

I recognise that there is lots of discussion about the value and safety of using memory mapped files within Rust and that Rust may not be the tool for the job here.

0

There are 0 best solutions below