我正在尝试使用 dnlib 库从 IL 指令生成 c# 代码。
我试图生成的代码是这个:
private string GetIp()
{
return new WebClient().DownloadString("https://api.myip.com/");
}
我的代码:
Type webclientType = typeof(System.Net.WebClient);
ConstructorInfo constructor = webclientType.GetConstructors()[0];
MethodInfo methodInfo = webclientType.GetMethod("DownloadString", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, System.Reflection.CallingConventions.Any, new Type[] { typeof(string) }, null);
MethodDefUser m = new MethodDefUser("GetIp", MethodSig.CreateInstance(module.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.Static | MethodAttributes.HideBySig)
{
Body = new CilBody()
};
m.Body.Instructions.Add(new Instruction(OpCodes.Newobj, constructor));
m.Body.Instructions.Add(new Instruction(OpCodes.Ldstr, "https://api.myip.com/"));
m.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, methodInfo));
m.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
尝试将模块保存到磁盘时出现错误(无效的指令操作数)。
现在我的代码正在生成这些指令:
newobj - Void .ctor()
ldstr - https://api.myip.com/
callvirt - System.String DownloadString(System.String)
ret -
当他们应该是这样的:
newobj - System.Void System.Net.WebClient::.ctor()
ldstr - https://api.myip.com/
callvirt - System.String System.Net.WebClient::DownloadString(System.String)
ret -
我试图替换constructor
变量webclientType
,但没有运气,也没有运气在网上找到任何信息。