Spence Green

التكرار يعلم الحمار

I work at Lilt. In addition to computers and languages, my interests include travel, running, and scuba diving. more...

Notifying Managed Code of a Native Callback

with 51 comments

Here’s a way for unmanaged code to notify managed code of a callback. The two code types use different calling conventions and the user cannot change the latter’s convention. Instead, use an inner class like this:

__gc classManagedClass
__nogc class UnmanagedClass
static void __cdecl MyCallback()
ManagedClass *mc = ManagedClass::GetClass();

ManagedClass *thisClass;

ManagedClass() { thisClass = this; }
static ManagedClass* GetClass() { return thisClass; }

void MyFunc() {}

The GetClass() method is a bit unsightly, but elegent nonetheless. The managed code can pass MyCallback to unmanaged code via a function pointer. The unmanaged code calls MyCallback and then MyCallback calls the managed method MyFunc(). This approach is especially useful for IJW DLLs in VC7.


Written by Spence

July 8th, 2005 at 8:38 am

Posted in .NET

Leave a Reply

You must be logged in to post a comment.