Write string data to MemoryMappedFile

后端 未结 3 1931
不思量自难忘°
不思量自难忘° 2021-02-06 13:03

I am following this tutorial here

I am having a hard time figuring out how to get a string \"THIS IS A TEST MESSAGE\" to store in the memory mapped file and then pull it

相关标签:
3条回答
  • 2021-02-06 13:46

    You can consider writing the length of the string and then the byte[] form of your string.
    For example if I would like to write "Hello" then I convert it into bytes:

    byte[] Buffer = ASCIIEncoding.ASCII.GetBytes("Hello");
    

    then do following while writing into the memory mapped file.

    MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000);
    MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
    accessor.Write(54, (ushort)Buffer.Length);
    accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
    

    While reading first go to position 54 and read 2 bytes holding length of your string. Then you can read an array of that length and convert it into string.

    MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000);
    MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
    ushort Size = accessor.ReadUInt16(54);
    byte[] Buffer = new byte[Size];
    accessor.ReadArray(54 + 2, Buffer, 0, Buffer.Length); 
    MessageBox.Show(ASCIIEncoding.ASCII.GetString(Buffer));
    
    0 讨论(0)
  • 2021-02-06 13:47

    I used this to write the characters of a string:

    string contentString = "Hello";
    char[] charsToWrite = contentString.ToCharArray();
    accessor.WriteArray(0, charsToWrite, 0, charsToWrite.Length);
    

    This wrote wide characters. Both C# and C++ programs were able to read the data as wide characters.

    0 讨论(0)
  • 2021-02-06 13:50

    It Works fine with CreateOrOpen instead of CreateNew! With the same code

    MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("test", 1000);
    MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
    accessor.Write(54, (ushort)Buffer.Length);
    accessor.WriteArray(54 + 2, Buffer, 0, Buffer.Length);
    

    and

    MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("test", 1000);
    MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
    ushort Size = accessor.ReadUInt16(54);
    byte[] Buffer = new byte[Size];
    accessor.ReadArray(54 + 2, Buffer, 0, Buffer.Length); 
    MessageBox.Show(ASCIIEncoding.ASCII.GetString(Buffer));
    
    0 讨论(0)
提交回复
热议问题