如何在C#中释放IntPtr? [英] How to free IntPtr in C#?
问题描述
如何释放ptrSentFromPinvokedDLL?
How to free ptrSentFromPinvokedDLL?
IntPtr ptrSentFromPinvokedDLL= IntPtr.Zero;
int resultFromVendor = CallVendorDll(ref ptrSentFromPinvokedDLL);
resultFromVendor = DoMoreWorkFromVendorDLL(
ptrSentFromPinvokedDLL, "workonthis");
// Free ptrSentFromPinvokedDLLhere
推荐答案
理想情况下,供应商对此感到担心,或者会有供应商功能来释放内存.如果不是,则需要知道供应商如何分配内存.例如,如果供应商使用 LocalAlloc
在kernel32.dll
中,则可以使用 CoTaskMemAlloc
然后使用 Marshal.FreeCoTaskMem(IntPtr)
用于释放内存.因此,请检查文档并据此进行.
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.
作为参考,这是一个不错的 MSDN文章关于内存分配模型.
For reference, here's a nice MSDN article about memory allocation models.
这篇关于如何在C#中释放IntPtr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!