Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize/deserialize an assembly object to and from a byte array

Let's say a create an (executable) assembly in memory by compiling a code string. Then I want to serialize this assembly object into a byte array and then store it in a database. Then later on I want to retrieve the byte array from the database and deserialize the byte array back into an assembly object, then invoke the entry point of the assembly.

At first I just tried to do this serialization like I would any other simple object in .net, however apparently that won't work with an assembly object. The assembly object contains a method called GetObjectData which gets serialization data necessary to reinstantiate the assembly. So I'm somewhat confused as to how I piece all this together for my scenario.

The answer only needs to show how to take an assembly object, convert it into a byte array, convert that back into an assembly, then execute the entry method on the deserialized assembly.

like image 398
Beaker Avatar asked Dec 21 '22 08:12

Beaker


2 Answers

A dirty trick to get the assembly bytes using reflection:

  MethodInfo methodGetRawBytes = assembly.GetType().GetMethod("GetRawBytes", BindingFlags.Instance | BindingFlags.NonPublic);
  object o = methodGetRawBytes.Invoke(assembly, null);
  
  byte[] assemblyBytes = (byte[])o;

Explanation: at least in my sample (assembly was loaded from byte array) the assembly instance was of type "System.Reflection.RuntimeAssembly". This is an internal class, so it can be accessed only using reflection. "RuntimeAssembly" has a method "GetRawBytes", which return the assembly bytes.

like image 136
wknauf Avatar answered Dec 24 '22 00:12

wknauf


An assembly is more conveniently represented simply as a binary dll file. If you think of it like that, the rest of the problems evaporate. In particlar, look at Assembly.Load(byte[]) for loading an Assembly from binary. To write it as binary, use CompileAssemblyFromSource and look at the result's PathToAssembly - then File.ReadAllBytes(path) to obtain the binary from the file.

like image 33
Marc Gravell Avatar answered Dec 24 '22 00:12

Marc Gravell