Created
September 12, 2019 15:27
-
-
Save Const-me/49f3da0ae744194fbf5be53552735431 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Tested with .NET Core 2.2, will likely work with the rest of the runtimes | |
using System; | |
using System.Diagnostics; | |
using System.IO.MemoryMappedFiles; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
namespace MappedFileTest | |
{ | |
static class Program | |
{ | |
const int fileLength = 1024; | |
static IntPtr getRawPointer( this MemoryMappedViewAccessor acc ) | |
{ | |
return acc.SafeMemoryMappedViewHandle.DangerousGetHandle(); | |
} | |
static MemoryMappedFile createTest( string name, int length ) | |
{ | |
long size = length * 4; | |
MemoryMappedFile mmf = MemoryMappedFile.CreateNew( name, size ); | |
int[] data = Enumerable.Range( 0, length ).ToArray(); | |
using( var mma = mmf.CreateViewAccessor( 0, size ) ) | |
mma.WriteArray( 0, data, 0, length ); | |
return mmf; | |
} | |
static void Main( string[] args ) | |
{ | |
// Create a memory mapped file with a unique name | |
string name = Guid.NewGuid().ToString( "D" ).ToLowerInvariant(); | |
using( var file = createTest( name, fileLength ) ) | |
{ | |
// Open that file by name | |
using( var openned = MemoryMappedFile.OpenExisting( name, MemoryMappedFileRights.Read ) ) | |
using( var acc = openned.CreateViewAccessor( 0, fileLength * 4, MemoryMappedFileAccess.Read ) ) | |
{ | |
// Get raw pointer | |
IntPtr rawPointer = acc.getRawPointer(); | |
// Read a single int from unmanaged memory at that pointer | |
int i42 = Marshal.ReadInt32( rawPointer + 42 * 4 ); | |
Debug.Assert( 42 == i42 ); | |
Console.WriteLine( "{0}", i42 ); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment