pin_ptr of delegate that spans scope of function

G

Guest

I have a C++/CLI library and I'm calling a function, RegisterTraceGuids()
that takes a function callback as a parm. I need the callback function to be
a managed delegate. In order to do this I create a pin_ptr of the delegate
and then pass it to RegisterTraceGuids.

The problem is that pin_ptr's can only be defined within the scope of a
function, and cant be class members. So once the function that calls
RegisterTraceGuids() is over my pinned delegate gets unpinned. But my
callback could get called at anytime, long after the function goes out of
scope.

So how can I pin a delegate instance for a period longer than the scope of
one function?
 
B

Ben Voigt [C++ MVP]

john conwell said:
I have a C++/CLI library and I'm calling a function, RegisterTraceGuids()
that takes a function callback as a parm. I need the callback function to
be
a managed delegate. In order to do this I create a pin_ptr of the
delegate
and then pass it to RegisterTraceGuids.

The problem is that pin_ptr's can only be defined within the scope of a
function, and cant be class members. So once the function that calls
RegisterTraceGuids() is over my pinned delegate gets unpinned. But my
callback could get called at anytime, long after the function goes out of
scope.

So how can I pin a delegate instance for a period longer than the scope of
one function?

GCHandle is how you pin _data_ past function exit.

In your case, you need to be using Marshal.GetFunctionPointerForDelegate
instead.
 
G

Guest

Hey Ben,
Thanks for the response. I am using the
Marshal.GetFunctionPointerForDelegate, but had read that it returns just a
regular pointer, not a pinned pointer. Do I still need to use GCHandle? Or
will GetFunctionPointerForDelegate pinn it for me?
Thanks!

Turbo


:
 
B

Ben Voigt [C++ MVP]

john conwell said:
Hey Ben,
Thanks for the response. I am using the
Marshal.GetFunctionPointerForDelegate, but had read that it returns just a
regular pointer, not a pinned pointer. Do I still need to use GCHandle?
Or
will GetFunctionPointerForDelegate pinn it for me?

The docs explain that you still need to keep the delegate alive with a
managed reference... however as nearly as I can tell the native function
pointer doesn't need to be pinned in any way.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top