-3

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
    Please see https://stackoverflow.com/help/how-to-ask, this isnt a great question and will mainly attract various opinions. – Simon Price Jan 19 '21 at 21:45
  • @SimonPrice what's wrong with my question? I want to know if i have to free them manually or they'll be freed automatically – Amirreza Moeini Yegane Jan 19 '21 at 21:56
  • 1
    Without seeing your code, cannot definitively advise. But no, **you don't need either of these options at all** if you're not allocating any memory. Setting to `Zero` is a no-op as GC does nothing with an `IntPtr` anyway, it's just a number. – Charlieface Jan 19 '21 at 22:03
  • @Charlieface so i basically can leave my IntPtr's after I'm done with them? for example if i use `GetProcAddress` which returns an IntPtr, I can use the returned IntPtr and just leave it? am i right? – Amirreza Moeini Yegane Jan 19 '21 at 22:13
  • Correct, but **please [edit] and add your code to remove downvotes** – Charlieface Jan 19 '21 at 22:15
  • @Charlieface Thanks for your comment. I haven't write my code yet. – Amirreza Moeini Yegane Jan 19 '21 at 22:20

1 Answers1

2

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?

mm8
  • 163,881
  • 10
  • 57
  • 88