> > Thats why I thought I'd circumvent the issue by not using a GCHandle
> > at all while converting a System.Object^ to a void* and still be able
> > to run rude_code in a secondary appdomain.
>
> That will not work. You *must* either allocate a GCHandle or pin the object,
> otherwise the object is eligible for garbage collection.
Gotcha Jeroen. I understand perfectly. FWIW, the code I inherited
just allocates a GCHandle and never pins it (using that Pinned
enumeration Tamas was talking about elsethread). I wonder how it has
been working all these years.
> You can't really "convert" a managed reference to an unmanaged pointer. You
> can only temporarily create unmanaged pointers to managed objects.
[quoted text clipped - 7 lines]
>
> In general, no, it doesn't -- you must use delegates for that. Seehttp://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/
Wow! Thats *exactly* what I ran into. Thanks Jeroen! How in the
world do you guys keep track of things like this??!! Seems like an
obscure problem to me...
Jeroen Mostert - 01 Mar 2008 10:46 GMT
>>> Thats why I thought I'd circumvent the issue by not using a GCHandle
>>> at all while converting a System.Object^ to a void* and still be able
[quoted text clipped - 6 lines]
> enumeration Tamas was talking about elsethread). I wonder how it has
> been working all these years.
Allocating a GCHandle will prevent GC as well. Pinning is only necessary if
you need the address of the object in unmanaged code. The code fragment you
showed doesn't: it actually retrieves opaque handles when it calls
.ToIntPtr(), not direct pointers. These handles can be converted back and
passed to managed code for as long as the GCHandle remains allocated.
> Wow! Thats *exactly* what I ran into. Thanks Jeroen! How in the
> world do you guys keep track of things like this??!! Seems like an
> obscure problem to me...
I didn't keep track; I've never seen this problem before (I've worked with
callbacks into unmanaged code and separate appdomains, just not in
combination). I simply googled for "delegate unmanaged appdomain". The
supplied site is the first hit. Knowing that delegates should probably be
involved is a guess, granted.
Now that I have seen it, however, I will keep track, in case anyone around
me ever runs into it. Repeat until all-knowing! :-)

Signature
J.