Hej Erik,
> MyTest::setCallback(t,
>
>((MyTest::CallBackFunc)Marshal::GetFunctionPointerForDelegate(cb).ToPointer));
[...]
>The error is on the MyTest::setCallBack(...)-line and has error code C2440
>[1].
That's because you're not calling the ToPointer method, so you're
trying to cast the function itself rather than its return value. Add a
pair of parentheses after ToPointer and it should work.
Note also that the cb delegate is eligible for garbage collection
immediately after the GetFunctionPointerForDelegate call, which would
render the function pointer stored in the native code invalid. You
have to keep a reference to the delegate alive as long as the function
pointer is in use to prevent this from happening.
And finally, you should use the UnmanagedFunctionPointer attribute on
the CallBack delegate to set the calling convention to cdecl to match
the CallBackFunc signature.
Mattias

Signature
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Erik Wikström - 07 Mar 2007 07:27 GMT
On 6 Mar, 21:46, Mattias Sjögren <mattias.dont.want.s...@mvps.org>
wrote:
> Hej Erik,
>
[quoted text clipped - 5 lines]
> trying to cast the function itself rather than its return value. Add a
> pair of parentheses after ToPointer and it should work.
Yes, of course, should have notices that myself.
> Note also that the cb delegate is eligible for garbage collection
> immediately after the GetFunctionPointerForDelegate call, which would
> render the function pointer stored in the native code invalid. You
> have to keep a reference to the delegate alive as long as the function
> pointer is in use to prevent this from happening.
I'll keep that in mind, thanks for telling.
> And finally, you should use the UnmanagedFunctionPointer attribute on
> the CallBack delegate to set the calling convention to cdecl to match
> the CallBackFunc signature.
Yes, it all works like a charm now. Thank you very much.
--
Erik Wikström