Search:
Namespaces
Discussions
.NET v1.1
Feedback
Callback issue again.
Messages
Related Types
This message was discovered on
microsoft.public.dotnet.framework.interop
.
Responses highlighted in red are from those people who are likely to be able to contribute good, authoratitive information to this discussion. They include Microsoft employees, MVP's and others who IMHO contribute well to these kinds of discussions.
Post a new message to this list...
Tamas Karoly via .NET 247 (VIP)
Hi Guys,
This might have come up several times, but I still have problems with calling a managed object's member function from an unmanaged function. Here is what I was trying to do:
-------- unmanaged code -------
typedef void (*CALLBACK_FN)();
static CALLBACK_FN mFn = NULL;
void SetCallbackFn(CALLBACK_FN Fn)
{
mFn = Fn;
}
void CallCallbackFn()
{
mFn();
}
-------- managed code -------
public __delegate void ManagedCallback();
public __gc class CManagedWrapper
{
GCHandle mFnHandle;
public:
void SetCallback(ManagedCallback* Fn)
{
mFnHandle = GCHandle::Alloc(Fn);
SetCallbackFn((CALLBACK_FN)Fn);
}
void ReleaseCallback()
{
mFnHandle.Free();
}
void CallFunction()
{
CallCallbackFn();
}
};
When I call CManagedWrapper.CallFunction() I receive an 'Object reference was not set to an instance of an object' error, although I called SetCallback() with param new ManagedCallback(<some function in an object>). I guess the problem is that I simply comvert the delegate to a c-style function pointer. However, the
GCHandle
.Alloc() should pin the object.
Could you please tell me what's wrong with this code or suggest any other way to achieve the same result?
Thank you,
Tamas Karoly
-----------------------
Posted by a user from .NET 247 (
http://www.dotnet247.com/
)
<Id>lFOSqu6GiUyAwDyD99weyA==</Id>
Reply to this message...
Mattias Sjögren
Tamas,
>However, the
GCHandle
.Alloc() should pin the object.
No, since you're not allocating a pinning handle. And even if you
were, a pointer to a pinned delegate isn't the same as a function
pointer.
>Could you please tell me what's wrong with this code or suggest any other way to achieve the same result?
Have a look at
http://www.codeproject.com/managedcpp/cbwijw.asp
Mattias
--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
|
http://www.dotnetinterop.com
Please reply only to the newsgroup.
Reply to this message...
System.Runtime.InteropServices.GCHandle
Ad
MBR BootFX
Best-of-breed application framework for .NET projects, developed by Matthew Baxter-Reynolds and MBR IT
Copyright © Matthew Baxter-Reynolds 2001-2008. '.NET 247 Software Development Services' is a trading style of MBR IT Solutions Ltd.
Contact Us
-
Terms of Use
-
Privacy Policy
-
www.dotnet247.com