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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With