Reputation: 410
I am using GCHandle::FromIntPtr to convert unmanaged structure pointer to managed object reference follow an example in msdn. Below is my code snippet:
GCHandle gch = GCHandle::FromIntPtr(IntPtr(someNativePtr));
MyManagedClass^ obj = static_cast<MyManagedClass^>(gch.Target);
My question is should I free gch?
UPDATE: There's a huge problem in this question just as Medinoc mentioned in his comment: GCHandle::FromIntPtr can not accept an IntPtr which points to an unmanaged object!!! So the question is completely pointless.
Upvotes: 4
Views: 1815
Reputation: 111
I couldn't understand it from the answer provided… As of my understanding: Using GCHandler.Alloc it prevents the gc from collecting that allocated object, so it can be passed around to unmanaged code etc. if you dont save the address somewhere to that now unmanaged object the object will stay in memory indefinitely.
GCHandle is just an 'interface' for an unmanaged object in memory. You can call as many FromIntPtr as you wish. This wont overflow your memory as there still is only that one object you deal with. It doesnt create another one out of thin air. Doing GCHandle.Free doesnt delete the handle it passes the object to the gc.
Correct me if I am wrong
Upvotes: 0
Reputation: 7290
FromIntPtr method returns a new GCHandle (value-type) struct created from a handle to a managed object, while Alloc method Allocates a handle for the specified object.
So you need to call Free() on the GCHandle struct only if you got it by a call to Alloc() not FromIntPtr()
Reference:
Upvotes: 4
Reputation: 6608
The MSDN doc doesn't say you can create a GCHandle out of thin air from a random IntPtr
that doesn't even point to a managed object. It says you can convert a GCHandle
into an IntPtr
and back into a GCHandle
for the purpose of passing it as context through unmanaged functions (that by definition only accept pointers or intptr_t
-like types)
As a consequence, the only kind of IntPtr
you're supposed to pass to GCHandle::FromIntPtr()
is one that was returned by GCHandle::ToIntPtr()
.
Upvotes: 4