using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Iced.Intel; using static Iced.Intel.AssemblerRegisters; var asm = new Assembler(64); var msgHello = asm.CreateLabel(); asm.push(rbp); asm.mov(rbp, rsp); asm.push(rsi); asm.push(rdi); asm.push(r15); asm.push(r14); // label address to register --- mov rcx, msgHello asm.lea(rcx, __[msgHello]); asm.call((ulong)typeof(Test).GetMethod(nameof(Test.UnsafeWriteCString))!.MethodHandle.GetFunctionPointer()); asm.pop(r14); asm.pop(r15); asm.pop(rdi); asm.pop(rsi); asm.mov(rsp, rbp); asm.pop(rbp); asm.ret(); asm.Label(ref msgHello); asm.db("Hello, World!\n\r\0"u8); unsafe { var func = AsmExecutor.MakeFunction(asm); Console.WriteLine(func()); Console.WriteLine("Hi"); } public class Test { [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static unsafe void UnsafeWriteCString(byte* ptr) { while (*ptr != '\0') { Console.Write((char)*ptr); ptr++; } } } public static partial class AsmExecutor { private const uint PageExecuteReadwrite = 0x40; private const uint MemCommit = 0x1000; [LibraryImport("kernel32.dll", SetLastError = true)] private static partial IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); public static unsafe delegate* MakeFunction(Assembler asm) { const ulong rip = 0x10; var stream = new MemoryStream(); asm.Assemble(new StreamCodeWriter(stream), rip); var ptr = VirtualAlloc(IntPtr.Zero, (uint)stream.Length, MemCommit, PageExecuteReadwrite); Marshal.Copy(stream.ToArray(), 0, ptr, (int)stream.Length); return (delegate*)ptr; } }