I am working on a system that uses IntPtr’s returned from two separate C++ DLLs. The unmanaged memory is freed by calling the OBJECT_FREE method presented in each DLL.
Unfortunately, some of the code loses track of which DLL originally allocated the memory. This results in an access violation since we have moved to Win7 (for some reason we were getting away with it on WinXP).
In the medium term, I will have to wrap up every IntPtr to deal with this properly, but in the short term, is there any way to determine which DLL allocated the memory originally?
No – an
IntPtris just a simple wrapper around an integer (actually a pointer) – there is no additional metadata and its obviously impossible to tell just from a number where it came from.If you need to free memory associated with the
IntPtrthen I recommend that you implement a safe handle for each of your two separate C++ DLLs and modify your PInvoke calls to use safe handles instead, for example:Using safe handles instead of
IntPtroffers a number of other advantages as well seamlessly keeping track of the proper way of freeing resources associated with theIntPtr.See this MSDN blog article on safe handles to learn more.