Search code examples
c#memory-mapped-files

Memory mapped, can I synchronize an object with a memory location?


So I have a memory segment in a shared memory file which in C is structured with a fixed size array of buffer elements at the end. Size I can't have fixed size arrays in C# at the end of a struct I have created a buffer struct to encapsulate this and just read them after reading the header, all this works fine.

struct SDKHeader {
    int a;
    int b;
    int numBuf; //Number of buffers to read from
    long c;
}

struct SDKBuffer 
{
    int size;
    int location; //Position in shared memory
}

Boiled down code this is how I read it:

memoryMap = MemoryMappedFile.OpenExisting(MemMapFilename);
memoryAccessor = memoryMap.CreateViewAccessor();

int headerSize = Marshal.SizeOf(typeof(SDKHeader));
memoryAccessor.Read(0, out header);

int bufferSize = Marshal.SizeOf(typeof(SDKBuffer));
buffers = new SDKBuffer[header.numBuf];
for(int i = 0; i < header.numBuf; i++)
{
    memoryAccessor.Read(headerSize + i * bufferSize, out buffers[i]);
}

My issue is that this structure is updated quite a few times per second and in C it's as easy as pHeader = (HeaderType *)pSharedMem; to allow raw access to the data without continously reading it into another area. Is this at all possible in C#? Somehow make a connection between a struct and a memorylocation in the shared memory?


Solution

  • You can do the same thing in C# with unsafe code. The same code just works (var pHeader = (HeaderType*)pSharedMem;).

    Of course there are requirements to satisfy to use unsafe code and to be able to use structs in this way. A web search will easily turn them up.