如何用Dnlib导入.NET Framework 4.8运行时类型与方法并解决版本问题
问题
我的项目基于.NET Core 7.0,目标模块是.NET Framework 4.8。使用Dnlib导入GetString方法并注入至目标模块时,生成的exe会因为引用了.NET Core 7.0版本的依赖DLL而非4.8版本,导致找不到DLL崩溃。相关代码如下:
.... .... body.Instructions.Add(new Instruction(OpCodes.Call, module.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { })))); ..... ..... body.Instructions.Add(new Instruction(OpCodes.Callvirt, module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]), typeof(Int32), typeof(Int32) }))));
截图显示:生成的目标模块中,
Encoding.UTF8和GetString方法的引用指向了.NET Core 7.0版本的System.Private.CoreLib,而非.NET Framework 4.8对应的mscorlib或System.Runtime。
解决方案
不要直接用typeof(Encoding)从当前.NET Core 7.0运行时获取方法,而是手动构造.NET Framework 4.8对应的方法引用:
明确指定目标模块的程序集引用
先获取目标模块(.NET Framework4.8)对应的核心程序集,再从中查找Encoding类型:// 获取目标模块中的mscorlib程序集(.NET Framework 4.8的核心程序集) var targetAssembly = module.FindAssembly("mscorlib") ?? module.FindAssembly("System.Runtime"); var encodingType = targetAssembly.FindType("System.Text.Encoding");导入目标框架的
get_UTF8属性和GetString方法
从找到的encodingType中获取对应成员,再导入到目标模块:// 导入get_UTF8属性的get方法 var utf8Getter = encodingType.FindMethod("get_UTF8"); body.Instructions.Add(new Instruction(OpCodes.Call, module.Import(utf8Getter))); // 导入GetString方法(byte[], int, int重载) var getStringMethod = encodingType.FindMethod( "GetString", new[] { module.CorLibTypes.Byte.MakeArrayType(), module.CorLibTypes.Int32, module.CorLibTypes.Int32 } ); body.Instructions.Add(new Instruction(OpCodes.Callvirt, module.Import(getStringMethod)));验证引用目标
注入完成后,检查生成的模块引用,确认方法指向的是.NET Framework 4.8的程序集(如mscorlib, Version=4.0.0.0),而非.NET Core的System.Private.CoreLib。
这样就能确保注入的方法引用的是目标框架的版本,避免运行时因找不到依赖DLL崩溃。
内容的提问来源于stack exchange,提问作者Wael
相关产品推荐
相关产品推荐

