我有一个C#项目,我想用dnlib修改它。我可以在很好的范围内添加代码。但是,我无法找到添加DLLImport的方法,所有的搜索结果都是干涸的。我怎么能做到这一点?能办到吗?
编辑:我挖掘了dnSpy的源代码并找到了一种方法。我把它放在这里是为了让每个人都能看到:
var _loadedEXE = ModuleDefMD.Load("EXE.exe");
var _dllReference = new ModuleRefUser(_loadedEXE, "DLL_NAME.dll");
var _flagsDLL = MethodAttributes.PinvokeImpl | MethodAttributes.Public | MethodAttributes.Static;
var _flagsPDLL = MethodImplAttributes.PreserveSig;
var _mapDLL = new ImplMapUser(_dllReference, "", PInvokeAttributes.CallConvCdecl);
var _method = new MethodDefUser("METHOD_NAME", MethodSig.CreateStatic(_loadedEXE.CorLibTypes.Int32, _loadedEXE.CorLibTypes.Int32), _flagsPDLL, _flagsDLL);
_method.ImplMap = _mapDLL;这将导致dnSpy中的以下分解:
[DllImport("DLL_NAME.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int METHOD_NAME(int);我希望这对你有帮助,这样你就不会像我一样受苦。
发布于 2022-10-25 20:06:03
用dnlib实现VirtualProtect
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
internal static extern bool VirtualProtect(IntPtr address, IntPtr size, uint newProtect, out uint oldProtect);var virtualProtectNativeMethodAttributes = MethodAttributes.PinvokeImpl | MethodAttributes.Assembly | MethodAttributes.Static;
var virtualProtectNativeMethodImplementationAttributes = MethodImplAttributes.PreserveSig;
var dllReference = new ModuleRefUser(moduleDefMD, "kernel32.dll");
var nativeMethodName = "VirtualProtect";
var implementationMap = new ImplMapUser(dllReference, nativeMethodName, PInvokeAttributes.CharSetAuto | PInvokeAttributes.CallConvWinapi);
var virtualProtectNativeMethod = new MethodDefUser(nativeMethodName,
MethodSig.CreateStatic(moduleDefMD.CorLibTypes.Boolean, moduleDefMD.CorLibTypes.IntPtr, moduleDefMD.CorLibTypes.IntPtr, moduleDefMD.CorLibTypes.UInt32, moduleDefMD.CorLibTypes.UInt32),
virtualProtectNativeMethodImplementationAttributes, virtualProtectNativeMethodAttributes);
virtualProtectNativeMethod.ImplMap = implementationMap;
virtualProtectNativeMethod.ParamDefs.Add(new ParamDefUser("address", 1));
virtualProtectNativeMethod.ParamDefs.Add(new ParamDefUser("size", 2));
virtualProtectNativeMethod.ParamDefs.Add(new ParamDefUser("newProtect", 3));
virtualProtectNativeMethod.ParamDefs.Add(new ParamDefUser("oldProtect", 4, ParamAttributes.Out));https://stackoverflow.com/questions/66938326
复制相似问题