Using C/inline assembly in C#

前端 未结 2 1167
礼貌的吻别
礼貌的吻别 2021-01-31 05:12

Is there some method of using C source mixed with inline asm (this is not C++ code) in a C# app? I\'m not picky about how it gets done, if it requires compiling the C/

相关标签:
2条回答
  • 2021-01-31 05:39

    It's actually very easy and does not even require reflection.

            [SuppressUnmanagedCodeSecurity]
            [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
            private delegate int AssemblyAddFunction(int x, int y);
    
            [DllImport("kernel32.dll")]
            private static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
    
            ....................................
    
            byte[] assembledCode =
            {
                0x55,               // 0 push ebp            
                0x8B, 0x45, 0x08,   // 1 mov  eax, [ebp+8]   
                0x8B, 0x55, 0x0C,   // 4 mov  edx, [ebp+12]  
                0x01, 0xD0,         // 7 add  eax, edx       
                0x5D,               // 9 pop  ebp            
                0xC3                // A ret                 
            };
    
            int returnValue;
            unsafe
            {
                fixed (byte* ptr = assembledCode)
                {
                    var memoryAddress = (IntPtr) ptr;
    
                    // Mark memory as EXECUTE_READWRITE to prevent DEP exceptions
                    if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress,
                        (UIntPtr) assembledCode.Length, 0x40 /* EXECUTE_READWRITE */, out uint _))
                    {
                        throw new Win32Exception();
                    }
    
                    var myAssemblyFunction = Marshal.GetDelegateForFunctionPointer<AssemblyAddFunction>(memoryAddress);
                    returnValue = myAssemblyFunction(10, -15);
                }               
            }
    
            Console.WriteLine($"Return value: {returnValue}"); // Prints -5
    

    I have written a blog post on this: https://esozbek.me/inline-assembly-in-csharp-and-dotnet/

    0 讨论(0)
  • 2021-01-31 05:44

    Using inline assembly in C# is not a good idea.

    The concept of.NET IL is to be portable.

    Of you use online assembly then your code will not run on machines with different architecture such as ARM.

    0 讨论(0)
提交回复
热议问题