简体   繁体   中英

Read memory mapped file created by c++ into c#

Basically I have a binary file which was created using the c++ memory mapped library. I have all the information regarding the struct in c++. I am trying to read that binary file using memory mapped library in c#. Can someone show me any articles/blogs which show how to achieve that?

I am struggling at mapping the c++ struct to c# struct and also the steps required to read and map the content.

Thanks in advance.

First, open the file with a FileStream .

var stream = new FileStream(path, FileMode.Open, FileAccess.Read);

Then instantiate a BinaryReader from that stream. This isn't completely required, but makes working with binary data easier.

var reader = new BinaryReader(stream);

Next, read in as many bytes as the structure needs, as indicated by Marshal.SizeOf :

var bytes = reader.ReadBytes(Marshal.SizeOf(typeof (MyStruct)));

Then, we "pin" that managed memory so the GC doesn't move it, using GCHandle.Alloc :

var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

Finally, we convert that buffer to a managed structure, using Marshal.PtrToStructure :

var myStruct = (MyStruct)Marshal.PtrToStructure(
                   handle.AddrOfPinnedObject(), typeof (MyStruct));

Don't forget to free the GCHandle:

handle.Free();

    return theStructure;
}

Here is an example of part of that wrapped up in a generic function.


While I haven't tried it, I'm fairly confident this would also work with a using a MemoryMappedFile and calling CreateViewStream (which you pass to the BinaryReader .)

var mmfile = MemoryMappedFile.CreateFromFile(path);
var stream = mmfile.CreateViewStream();
var reader = new BinaryReader(stream);
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM