Skip to content

Instantly share code, notes, and snippets.

@ophura
Last active August 30, 2025 16:42
Show Gist options
  • Select an option

  • Save ophura/5e1f7051d81b120e1eb243ade2114657 to your computer and use it in GitHub Desktop.

Select an option

Save ophura/5e1f7051d81b120e1eb243ade2114657 to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
internal static unsafe partial class VirtualMemory
{
internal const uint Commit = 0x1000;
internal const uint Reserve = 0x2000;
internal const uint Release = 0x8000;
internal const uint PageExecuteReadWrite = 0x40;
[LibraryImport("kernel32", EntryPoint = "VirtualAlloc")]
internal static partial void* Alloc(void* address, nuint size, uint type, uint protection);
[LibraryImport("kernel32", EntryPoint = "VirtualFree")]
internal static partial void Free(void* address, nuint size, uint type);
}
internal sealed unsafe class InlineAssembly<TReturn> : IDisposable
where TReturn : unmanaged
{
private delegate* unmanaged<TReturn> _machineCode;
internal InlineAssembly(params ReadOnlySpan<byte> machineCode)
{
_machineCode = (delegate* unmanaged<TReturn>)VirtualMemory.Alloc(
null, (nuint)machineCode.Length,
VirtualMemory.Commit | VirtualMemory.Reserve,
VirtualMemory.PageExecuteReadWrite
);
machineCode.CopyTo(new Span<byte>(_machineCode, machineCode.Length));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal TReturn Execute() => _machineCode();
private void Dispose()
{
if (_machineCode is null) return;
VirtualMemory.Free(_machineCode, 0, VirtualMemory.Release);
_machineCode = null!;
}
void IDisposable.Dispose()
{
Dispose();
GC.SuppressFinalize(this);
}
~InlineAssembly() => Dispose();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment