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??
Your delegate
delegate void Write(string text);
accepting string as parameter so you need to do this before emittingcall
:And you must return in the end of the method so you need to do that:
Complete code:
Update: I noticed that you want to send parameter to method so instead of
Write this
Then what you send here
delegateVoid("test");
will print out.And about the access limitation, if you can't make
Program
class public, you can define yourDynamicMethod
like this to get access: