Clear unmanaged memory

Whenever I use one function from an unmanaged dll in Usercontrol I got this error. "System.AccessViolationException: An attempt was made to read or write protected memory. This often indicates that other memory is corrupted." But this only happens if I use this function so many times. But I need to use this function every 3 minutes. Any ideas are greatly appreciated. Thank.

+2


source to share


2 answers


From what you posted with very little information, my gut first answer would be that the unmanaged dll you are using, if written by a third party, has memory handling errors inside it. If it is a linked Windows DLL, you need to do more research on how you use it or the resources it uses, as this error is most likely caused by your code if it is a Windows DLL.



One thing you should look into is how your access to the shared data between your program and the external DLL is, perhaps some of your members should be marked volatile and use locking when processing them.

+1


source


Memory management in Marshalling is difficult. You give very less information, so I can answer in general:

Te Interop marshaller uses CoTaskMemFree and CoTaskMemAlloc to allocate memory. If your DLL is allocating memory and .NEt needs to free it (or vice versa), you should use these functions. If memory is allocated new or malloc () and freed with delete or free (), the library should provide some kind of Cleanup () function to handle this. To prevent the Marshaller from freeing memory, you must declare your functions with IntPtr as the parameter / return data type, and not use a string or whatever.

Consider the following declarations:



   [ DllImport( "Your.dll", CharSet=CharSet.Auto )]
   public static extern string GetSomeString();

   [ DllImport( "Your.dll", CharSet=CharSet.Auto )]
   public static extern IntPtr GetSomeString();

      

The first function should return the string allocated with CoTaskMemAlloc () and it is freed by the .NET Marshaller. The second function can return a string allocated by malloc or delete, but the memory is not automatically freed. You have to call the FreeMemory (IntPtr) function that the library should provide.

Be sure to read: .NET Default Marshaling Behavior

0


source







All Articles