Search code examples
.netvisual-c++c++-cli

Should I free the handle returned from GCHandle::FromIntPtr?


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.


Solution

  • 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().