How can I load a downloaded assembly into a Roslyn workspace in C #

I am improving the existing process with generating runtime code. The code that I create at runtime requires access to some of the same DLLs that the process creating the code already references.

The problem is that the process runs as part of a third-party software that downloads DLLs from resources and injects them into my process ... so I have no access to either the dll on disk or the resource that contains the DLL in the external shell.

As a result, I try to use the assemblies that I already have in memory and transfer them to the Roslyn workspace, in which I put my code at runtime for compilation. I thought I could try serializing the assembly with binary formatting according to this SO: The opposite operation is to load the assembly (byte [] rawAssembly)

But even if I pretty much take the code as it is:

Assembly yourAssembly = typeof(object).Assembly; var formatter = new BinaryFormatter(); var ms = new MemoryStream(); formatter.Serialize(ms, yourAssembly); var reloadedAssembly = Assembly.Load(ms.GetBuffer()); 

I get:

 An exception of type 'System.BadImageFormatException' occurred in mscorlib.dll but was not handled in user code 

None of the other search results seemed better.

I want to do something like:

 var assemblyRef = MetadataReference.CreateFromAssembly(typeof(object).Assembly); mySolution.AddMetadataReference(projectId, assemblyRef); 

Any suggestions?

+5
source share
1 answer

For a managed assembly loaded using Assembly.Load (byte []), you can create a MetaataReference Roslyn like this:

 var assembly = Assembly.Load(bytes); var modulePtr = Marshal.GetHINSTANCE(assembly.ManifestModule); var peReader = new PEReader((byte*)modulePtr, bytes.Length)) var metadataBlock = peReader.GetMetadata(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataBlock.Pointer, metadataBlock.Length); var assemblyMetadata = AssemblyMetadata.Create(moduleMetadata); var reference = assemblyMetadata.GetReference(); 

Please note that this does not work for assemblies loaded from a file, as the location in memory is different.

+1
source

Source: https://habr.com/ru/post/1259430/


All Articles