all groups > dotnet interop > november 2006 >
You're in the

dotnet interop

group:

Callbacks in C++, with managed delegates...


Callbacks in C++, with managed delegates... TT (Tom Tempelaere)
11/16/2006 6:56:02 AM
dotnet interop:
Hi all,

I have a problem with the project I am working on. Someone is coding a
driver in plain (unmanaged) C++, and it is required to subscribe a callback
for certain notifications. This driver is supposed to be used from a managed
environment though, so what I want to do is subscribe a managed delegate to a
certain callback in C++.

Suppose this callback in unmanaged C++ is defined like:

typedef void (__stdcall* CB)( void );

And I would get the unmanaged C++ library with an interface to register such
a callback:

class C {
public:
void Register_CB( CB cb ) { this->_cb = cb; }
private:
CB _cb;
void Invoke_CB( ) { (*_cb)( ); }
};

How would I go about registering a delegate to it? Any pointers or links
that could help me with this specific issue?

Kind regards,
--
RE: Callbacks in C++, with managed delegates... TT (Tom Tempelaere)
11/16/2006 8:11:02 AM
Hmm I found a way using GCHandle to fix the delegates, and using Marshal
class to do the interop...

My only concern is that if I would subscribe a lot of handlers that way, is
memory fragmentation due to all the pinning...

Regards,
--
Tom Tempelaere.


[quoted text, click to view]
Re: Callbacks in C++, with managed delegates... Marcus Heege
11/21/2006 6:24:30 PM
From your descriptions, I assume you are using
Marshal.GetFunctionPointerForDelegate.

In this case there is no need to fix delegates. Neither with GCHandle nor
via pinned pointers. The runtime generates a unmanaged -> managed thunk in
your case. This thunk is passed to the native function, not the delegate.
The only thing you must ensure that you hold a reference to the delegate as
long as the thunk is needed, because the lifetime of the target delegate
controls the lifetime of the thunk.

Marcus Heege

"TT (Tom Tempelaere)" <_|\|_0$P@|/\|titi____AThotmailD.Tcom|/\|@P$0_|\|_>
[quoted text, click to view]

AddThis Social Bookmark Button