Create delegate with reference to method in DLL

I have DLL with some methods. I load it in runtime and I want to create delegate to method that is located in DLL.

DLL:

public static Point Play(int[,] foo, int bar, int baz) { ... }

// ...

I want to create delegate to the Play method. There may be more methods in the DLL.

Code:

private delegate Point PlayDel(int[,] foo, int bar, int baz);

// ...

Assembly ass = Assembly.LoadFile(pathToMyDLL);
PlayDel dgt = // ???
Jon Skeet
people
quotationmark

You'd need to find the type containing the method first, then use Delegate.CreateDelegate:

Type type = ass.GetType("NameOfTypeContainingMethod");
PlayDel del = (PlayDel) Delegate.CreateDelegate(typeof(PlayDel), type, "Play");

Alternatively, you could get the MethodInfo and create the delegate from that:

Type type = ass.GetType("NameOfTypeContainingMethod");
MethodInfo method = type.GetMethod("Play");
PlayDel del = (PlayDel) Delegate.CreateDelegate(typeof(PlayDel), method);

If there are multiple methods called Play, you may need to call GetMethods() instead and find the right one (e.g. by parameter types) first.

people

See more on this question at Stackoverflow