Tuesday, July 26, 2005
Passing Function Pointer to Unmanaged Class from Managed Class
While working with the FlexLM library, I had to register some callbacks.
As I was working with managed C++, I had to come up with a way of passing a function pointer from my managed class to the unmanaged FLexLM library calls. (I am not using the DLL, but staticly linking to the FlexLM library).
What I found is there is no way to pass a managed function to the unmanaged function.
__gc public class managedClass
{
public:
void myCallBack()
{
}
managedClass()
{
//set_callback is a function from the unmanaged library
set_callback( (void*) myCallBack) //this wont work
}
}
The above code will not work and you will get a compiler error, which says something like cannot convert __gc* to void *.
I tried delegates which also wont work here.
One thing that one could do, is to create the myCallBack as a static function outside of the managedClass. This would work.
But to make my solution look elegant, what I did was to create a __nogc class which was nested within the managedClass.
__gc public class managedClass
{
private:
__nogc class unmanagedClass
{
public:
static void CallBack()
{
managedClass::Instance->myCallBack();
}
}
static managedClass *thisClass;
public:
void myCallBack()
{
}
__property static managedClass* get_Instance()
{
return thisClass;
}
managedClass()
{
thisClass = this;
//set_callback is a function from the unmanaged library
set_callback( (void*) unmanagedClass::CallBack) //this will work
}
}
By doing it like this, when the unmanaged library decides to call my unmanagedClass's CallBack, it will call the ManagedClass's instance's callback. I can then do custom processing thats tailored to the current instance!
Coolio!
No comments:
Post a Comment
Remember, if you want me to respond to your comment, then you need to use a Google/OpenID account to leave the comment.