Daniel wrote:
How do I call a delegate in late bound C# dll? there some way to do this w/
a sharedinterface file? any examples? i tried this but it doesnt work:
(oType.GetMetho d("IOCTLJOB").I nvoke(pObj, new object[] {
pClass1.m_job } )).ToString();
and it returns the error:
Additional information: Object type cannot be converted to target type.
I have the delegate defined in both the late bound dll and the host assembly
like this:
public delegate void Job();
Hi Daniel,
When you look at your assembly with ILDASM.exe, you will notice that
delegates are implemented as inner classes of your type. The name of
this inner class will be the name of your delegate type.
This inner class has a constructor, which takes:
- The outer instance
- A function pointer to the method that should be called
The delegate class also has an "Invoke" method, together with a
BeginInvoke and EndInvoke pair (if you want asynchronous activation).
Say, for example that you have this class:
public class MyClass
{
public MyClass()
{
}
public void Foo()
{
Console.WriteLi ne("test");
}
public delegate void Job();
}
In the above example, the "Foo" method is a method that can be invoked
through the delegate of type "Job".
Below is the code to do this invokation ( the comments should be self
explanatory)
//
// Load the type's assembly, Get the type, and create an instance
//
Assembly assembly =
AppDomain.Curre ntDomain.Load(" TestDelegateAss embly");
Type classType = assembly.GetTyp e("TestDelegate Assembly.MyClas s");
bject instance = Activator.Creat eInstance(class Type);
//
// Now, get the delegate (implemented as an inner class), and get
// a reference to a method ("Foo"), which has a signature
// that corresponds to the delegate
//
Type delegateType =
assembly.GetTyp e("TestDelegate Assembly.MyClas s+Job");
MethodInfo fooRef = classType.GetMe thod("Foo");
//
// We need to pass in a pointer to the function, so go ahead
// and get that one
//
IntPtr fooRefPtr = fooRef.MethodHa ndle.GetFunctio nPointer();
//
// Create an instance of the delegate inner class. We need
// to pass in a reference to the containing instance AND
// a reference to the method
//
object delegateInstanc e =
Activator.Creat eInstance(
delegateType,
new object[] { instance, fooRefPtr });
//
// All delegates expose the "Invoke" Method
//
MethodInfo invokeMethod = delegateType.Ge tMethod("Invoke ");
//
// Now we can "Invoke", the "Invoke" method ;-)
//
invokeMethod.In voke(delegateIn stance, null);
Hope this helps,
Bennie