Getting a pointer to a method (as IntPtr)

  • Thread starter Thread starter Rik Hemsley
  • Start date Start date
R

Rik Hemsley

How does one go about getting a pointer to method as an IntPtr?

Example:

public class A
{
public void X()
{
Y(Z);
}

public void Y(IntPtr z)
{
}

public void Z()
{
}
}

This won't compile, because the compiler thinks I meant Y(Z()).

I'm guessing this must be possible, because classes inheriting from
System.EventHandler have ctors which takes a parameter called 'method',
whose type is IntPtr.

Cheers,
Rik
 
Pete said:
What you want is a delegate.

See the ctor for System.Timers.ElapsedEventHandler.

I'm trying to instantiate that class (and any other EventHandler-derived
class) using ConstructorInfo.Invoke.

I am writing a unit test framework which allows testing of async code,
so tricky things like this are necessary.
There are no pointers, per se. Nothing you could use from
unmanaged code.

I'm using managed code only.

Quoting myself:

I'm guessing this must be possible, because classes inheriting from
System.EventHandler have ctors which takes a parameter called 'method',
whose type is IntPtr.

EventHandler-derived classes must be instantiated somehow. I just need
to know how!

Cheers,
Rik
 
Rik,

When creating delegates dynamically, you don't call the Invoke method on
the ConstructorInfo instance. Rather, you call the appropriate static
CreateDelegate method overload, which will take the Type information for the
delegate, the method info which you want to attach to, the instance, etc,
etc.

Once you have that, you can dynamically invoke your delegate calling the
DynamicInvoke method on the instance of the delegate.

Hope this helps.
 
Nicholas said:
Rik,

When creating delegates dynamically, you don't call the Invoke method on
the ConstructorInfo instance. Rather, you call the appropriate static
CreateDelegate method overload, which will take the Type information for the
delegate, the method info which you want to attach to, the instance, etc,
etc.

Once you have that, you can dynamically invoke your delegate calling the
DynamicInvoke method on the instance of the delegate.

Hope this helps.

That's exactly what I was looking for, thanks very much.

Rik
 
Back
Top