Last active
August 30, 2025 16:42
-
-
Save ophura/5e1f7051d81b120e1eb243ade2114657 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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