I have a program stored in byte array.
Is it possible to run it inside C#?
I have a program stored in byte array.
Is it possible to run it inside C#?
Yes. This answer shows you can directly execute the contents of a byte array. Basically, you use VirtualAlloc
to allocate an executable region on the heap with a known address (a IntPtr
). You then copy your byte array to that address with Marshal.Copy
. You convert the pointer to a delegate with GetDelegateForFunctionPointer
, and finally call it as a normal delegate.
Sure.
.exe
file.Process
class to execute the file.Note: this is assuming that your byte array is executable code, and not source code. This also assumes that you have a valid PE header or know how to make one.
Assuming the byte array contains a .net assembly (.exe or .dll):
Assembly assembly = AppDomain.Load(yourByteArray)
Type typeToExecute = assembly.GetType("ClassName");
Object instance = Activator.CreateInstance(typeToExecute);
Now, if typeToExecute implements an interface known to your calling program, you can cast it to this interface and invoke methods on it:
((MyInterface)instance).methodToInvoke();
If the byte array is a .Net assembly with an EntryPoint
(Main method) you could just do this. Most of the time returnValue
would be null
. And if you wanted to provide command line arguments you could put them in the commandArgs
string listed below.
var assembly = Assembly.Load(assemblyBuffer);
var entryPoint = assembly.EntryPoint;
var commandArgs = new string[0];
var returnValue = entryPoint.Invoke(null, new object[] { commandArgs });
You can create a virtual machine and execute the code OR you could use reflection and dynamic types to create a dynamic assembly, potentially. You can dynamically load assembly.
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx
You could thus perhaps do something with that. If my memory serves me though there are some limitations.
See
Reflection Assembly.Load Application Domain