Is it possible to use managed pointers to alter a .NET assembly once it has been loaded into memory?
Given that the .NET metadata table format contains actual RVAs that show开发者_JAVA百科 where an assembly might be located in memory, would it be possible to use managed pointers on the CLR to access the places in memory where the assembly is being stored so that it can be modified after it has been loaded into memory?
Technically yes, it's possible (assuming FullTrust+unsafe code)- pointers are pointers, and managed code is really unmanaged code once it's been JIT'ed. That said, it seems like a recipe for disaster for anything beyond experimentation. You wouldn't be able to modify the IL, since it may have already been JIT'ed, so you'd have to go find the JIT'ed code, and hope that the CLR doesn't relocate it out from underneath you or re-JIT the code (both of which it's allowed to do).
If you really want to do this, there are easier ways- some metaprogramming/mocking frameworks use the CLR Profiling API to accomplish similar tricks (run before, run after, replace method impl, etc). Even that I wouldn't put into production though- easy way to cause a resume-producing-event, as those hooks aren't really tested for stability to the same degree (eg, they leak, fail in strange ways, etc). :)
精彩评论