Managed C++ How to pass a pointer to a class instance to a static callback?
Posted on 2008-01-29
So in my quest to integrate a native C++ dll callback into a managed C++ project, I have now succeeded (with much help!) to import the dll calls including the callback call into the project by the use of delegates. The callback is a static member function of a managed class, in fact the class of the only Form of that small .NET project.
Now my problem is that I don't know how to get access to the members of the managed class from the callback function. Indeed since it is a static function, I cannot use the handy "this->" function.
Back in the MFC days, I would have used the AfxGetApp() function to grant me access to the outside world, is there an equivalent in .NET?
Another option might be this: I can pass a "void* pContext" pointer to the dll function which registers the callback function. So I thought I should cast the "this" pointer to my Form class instance to a "void*" pointer and do the reverse from inside my callback.
The code looks like this :
typedef void (__clrcall *func_t2)(TestCamera2::Form1 ^const);//for casting from a Form^ type to a void* type
func_t fp2 = func_t(Marshal::GetFunctionPointerForDelegate(fp).ToInt32());//delegate to the callback function
m_lCallbackRegistration = CameraAddStreamingCallback(m_hCamera, fp2, func_t2(this));//this compiles fine
Then in my callback I have to cast back my pContext pointer from void* to Form^.
I tried to do it the following way:
typedef TestCamera2::Form1 ^const (__clrcall *func_t3)(System::Void*);
func_t3(pContext)->Preview->Name = L"Preview";//doing something on a member of the Form class
However I get the following compiler error which makes me think that my cast did not succeed:
error C2227: left of '->Preview' must point to class/struct/union/generic type
What am I doing wrong...?