Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

interop - How to free IntPtr in C#?

How to free ptrSentFromPinvokedDLL?

IntPtr ptrSentFromPinvokedDLL= IntPtr.Zero;

int resultFromVendor = CallVendorDll(ref ptrSentFromPinvokedDLL);

resultFromVendor = DoMoreWorkFromVendorDLL(
    ptrSentFromPinvokedDLL, "workonthis");

// Free ptrSentFromPinvokedDLLhere
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...