jbevain / cecil

Cecil is a library to inspect, modify and create .NET programs and libraries.
MIT License
2.77k stars 630 forks source link

Is there a simple way to replace an assembly reference without a full import? #731

Closed Serg046 closed 3 years ago

Serg046 commented 3 years ago

I have two assemblies A.dll and B.dll. I read A.dll, change its methods and then save it. One method "TestA()" has a reference to the method "TestB()" from B.dll and the thing is that I need to change some stuff inside "TestB()". If I just changed it through A.dll and then saved, my changed wouldn't be applied, the old B.dll would be in use. My idea is to save new B_patched.dll and override Domain.AssemblyResolve so that it loads B_patched.dll instead of B.dll. But if I didn't replace an assembly reference inside TestA() from B.dll to B_patched.dll, it wouldn't work, it would still use B.dll.

I understand that I could import the right method using ImportReference(MethodDefinition) but it is too complex and inefficient. The question is if I can replace a reference using a way like this:

var testA = asmA.Types[X].Methods[Y];
var testBReference = testA.Body.Instructions[Z].Operand as MethodReference;
testBReference.Module.Name += "_patched";