So I try to call a method from an extern DLL via a dynamicmethod using the ilgenerator.
delegate void Write(string text);
static void Main(string[] args)
{
byte[] bytes = File.ReadAllBytes(@"externmethod.dll");
var assembly = Assembly.Load(bytes);
var method = assembly.GetTypes()[0].GetMethod("Write");
var dynamicMethod = new DynamicMethod("Write", typeof(void), new Type[] { typeof(string) });
var ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.EmitCall(OpCodes.Call, method, null);
var delegateVoid = dynamicMethod.CreateDelegate(typeof(Write)) as Write;
delegateVoid("test");
Console.ReadLine();
}
And the DLL code:
using System;
class program
{
public static void Write(string text)
{
Console.WriteLine(text);
}
}
But I'm getting this strange error:
An unhandled exception of type 'System.InvalidProgramException' occurred in test.exe
Additional information: Common Language Runtime detected an invalid program.
And I don't have any clue what im doing wrong??