gpt4 book ai didi

c# - 是否可以从 C# 中执行 x86 汇编序列?

转载 作者:IT王子 更新时间:2023-10-29 04:21:21 24 4
gpt4 key购买 nike

继续我的逆向工程教育,我经常希望能够复制部分 x86 汇编代码,并从我选择的高级语言中调用它进行测试。

有人知道从 C# 方法中调用 x86 指令序列的方法吗?我知道这可以使用 C++ 完成,但我很好奇它是否可以在 C# 中完成?

注意:我不是在谈论执行 MSIL 指令。我说的是执行一系列原始 x86 汇编指令。

最佳答案

为了反驳 Brian 的说法,重写了 leppie 的回答中的代码 link :

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace DynamicX86
{
class Program
{
const uint PAGE_EXECUTE_READWRITE = 0x40;
const uint MEM_COMMIT = 0x1000;

[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

private delegate int IntReturner();

static void Main(string[] args)
{
List<byte> bodyBuilder = new List<byte>();
bodyBuilder.Add(0xb8);
bodyBuilder.AddRange(BitConverter.GetBytes(42));
bodyBuilder.Add(0xc3);
byte[] body = bodyBuilder.ToArray();
IntPtr buf = VirtualAlloc(IntPtr.Zero, (uint)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(body, 0, buf, body.Length);

IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));
Console.WriteLine(ptr());
}
}
}

关于c# - 是否可以从 C# 中执行 x86 汇编序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/959087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com