11

How to free ptrSentFromPinvokedDLL?

IntPtr ptrSentFromPinvokedDLL= IntPtr.Zero;

int resultFromVendor = CallVendorDll(ref ptrSentFromPinvokedDLL);

resultFromVendor = DoMoreWorkFromVendorDLL(
    ptrSentFromPinvokedDLL, "workonthis");

// Free ptrSentFromPinvokedDLLhere
2
  • 4
    Well, how did the vendor allocate the pointer? Use the corresponding deallocator. Commented Jan 29, 2010 at 0:42
  • Presuming you even need to free it.
    – Michael
    Commented Jan 29, 2010 at 0:50

2 Answers 2

10

Ideally either the vendor worries about this or there would be a vendor function for deallocating the memory. If not, you need to know how the vendor allocated the memory. For example, if the vendor allocated the memory using LocalAlloc in kernel32.dll then you could free the memory using Marshal.FreeHGlobal(IntPtr). Similarly, if the COM memory allocator CoTaskMemAlloc was used then Marshal.FreeCoTaskMem(IntPtr) would be used to free the memory. So check the documentation and proceed accordingly.

For reference, here's a nice MSDN article about memory allocation models.

0
1

There is no way of knowing how to free it or if it even needs to be freed without seeing the code inside CallVendorDll. (Or some documentation)

Not the answer you're looking for? Browse other questions tagged or ask your own question.