Skip to content

Commit

Permalink
Eliminate need to copy the linked memory
Browse files Browse the repository at this point in the history
  • Loading branch information
sliekens committed Sep 17, 2023
1 parent 703475e commit 4515ff2
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions GW2SDK/Internal/MumbleLink.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Buffers;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
Expand All @@ -18,10 +17,6 @@ internal sealed class MumbleLink : IDisposable
/// <remarks>Obtained with Process Explorer.</remarks>
private const int Length = 0x2000;

private readonly byte[] buffer;

private readonly GCHandle bufferHandle;

private readonly MemoryMappedFile file;

private readonly MemoryMappedViewAccessor view;
Expand All @@ -32,8 +27,6 @@ private MumbleLink(MemoryMappedFile file)
{
this.file = file;
view = file.CreateViewAccessor(0, Length, MemoryMappedFileAccess.Read);
buffer = ArrayPool<byte>.Shared.Rent(Length);
bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
}

public void Dispose()
Expand All @@ -42,10 +35,6 @@ public void Dispose()
{
view.Dispose();
file.Dispose();

// ReSharper disable once PossiblyImpureMethodCallOnReadonlyVariable
bufferHandle.Free();
ArrayPool<byte>.Shared.Return(buffer);
}

disposed = true;
Expand All @@ -68,9 +57,7 @@ public static MumbleLink CreateOrOpen(string name)

try
{
return new MumbleLink(
MemoryMappedFile.CreateOrOpen(name, Length)
);
return new MumbleLink(MemoryMappedFile.CreateOrOpen(name, Length));
}
finally
{
Expand All @@ -85,15 +72,19 @@ public T GetValue<T>() where T : struct
throw new ObjectDisposedException(nameof(MumbleLink));
}

var buffered = view.ReadArray(0, buffer, 0, Length);
if (buffered != Length)
var success = false;
try
{
throw new InvalidOperationException(
$"Expected {Length} bytes but received {buffered}. This usually indicates concurrent access to the current object, which is not supported."
);
view.SafeMemoryMappedViewHandle.DangerousAddRef(ref success);
var location = view.SafeMemoryMappedViewHandle.DangerousGetHandle();
return Marshal.PtrToStructure<T>(location);
}
finally
{
if (!success)
{
view.SafeMemoryMappedViewHandle.DangerousRelease();
}
}

// ReSharper disable once PossiblyImpureMethodCallOnReadonlyVariable
return Marshal.PtrToStructure<T>(bufferHandle.AddrOfPinnedObject());
}
}

0 comments on commit 4515ff2

Please sign in to comment.