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.
It depends on the native implementation of
CreatePartbut typically by passing the returned pointer to another native method calledDestroyPartor something when you are done with it.Whether you can actually use
Marshal.FreeHGlobalto 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
IntPtritself is just a value type:Just what is an IntPtr exactly?