Should I free all of IntPtr's with FreeHGlobal once I'm done with them?

135 Views Asked by At

I have a lot of IntPtr's in my project, some of them have been returned from a my dll, hence, I have not allocated memory for them using Marshal.AllocHGlobal()

[DllImport(Dll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr CreatePart(IntPtr partId);

How should I free these IntPtrs that are being returned from a dll fuction?

Marshal.FreeHGlobal() or variable = IntPtr.Zero or Both?

I've read some questions on this website and Microsoft doc, They're saying that Marshal.FreeHGlobal should be used for any memory that has been alocated using Marshal.AllocHGlobal. what if we haven't allocate memory for an IntPtr

Thanks for reading my question.

1

There are 1 best solutions below

0
mm8 On

How should I free these IntPtrs that are being returned from a dll fuction?

It depends on the native implementation of CreatePart but typically by passing the returned pointer to another native method called DestroyPart or something when you are done with it.

Whether you can actually use Marshal.FreeHGlobal to free the memory depends on the implementation of the native method that allocates the memory. The way you free the memory must match the way in which you have allocated the memory.

An IntPtr itself is just a value type:

Just what is an IntPtr exactly?