Florian,
thank you for your reply but I'm afraid it doesn't work. The Dll project
compiles fine but as soon as I run my C# test app I get an
ArgumentException ("Object contains non-primitive or non-blittable
data."). Seems like GCHandle::Alloc() has a problem with my delegate ...
Any suggestions?
Ahh, true, you are completely correct.
Thinking more closely to what you want to do, I realize you might not need
to actually pin the delegate at all; just keep a reference to it alive so
that it is not garbage collected (it actually does *not* matter that it
moves around in memory, as that won't affect the call to it from unmanaged
code in this particular case).
I looked around to verify this, and found what I was looking for:
http://blogs.msdn.com/cbrumme/archiv.../06/51385.aspx
Here, Chris Brumme explains in detail:
"Along the same lines, managed Delegates can be marshaled to unmanaged code,
where they are exposed as unmanaged function pointers. Calls on those
pointers will perform an unmanaged to managed transition; a change in
calling convention; entry into the correct AppDomain; and any necessary
argument marshaling. Clearly the unmanaged function pointer must refer to a
fixed address. It would be a disaster if the GC were relocating that! This
leads many applications to create a pinning handle for the delegate. This
is completely unnecessary. The unmanaged function pointer actually refers
to a native code stub that we dynamically generate to perform the transition
& marshaling. This stub exists in fixed memory outside of the GC heap.
However, the application is responsible for somehow extending the lifetime
of the delegate until no more calls will occur from unmanaged code. The
lifetime of the native code stub is directly related to the lifetime of the
delegate. Once the delegate is collected, subsequent calls via the
unmanaged function pointer will crash or otherwise corrupt the process. In
our recent release, we added a Customer Debug Probe which allows you to
cleanly detect this – all too common – bug in your code. If you haven’t
started using Customer Debug Probes during development, please take a look!"
Hope this helps!
--
Tomas Restrepo
to****@mvps.org http://www.winterdom.com/