tags:

views:

274

answers:

2

Hi all, Whenever i use one function from unmanaged dll in Usercontrol, I got this error. "System.AccessViolationException: Attempted to read or write protected memory. This is often a indication that other memory is corrupt." But it only happens if I use this function so many times. But I need to use this function every 3 minutes. Any ideas is much appreciated.Thank you.

+1  A: 

From what you've posted with very little information my first gut response would be that the unmanaged dll your using if it was written by a 3rd party has memory handling faults inside it. If it's an included windows DLL you need to do more research on how your using it, or the into the resources its using as this error is most likely caused by your code if it's a windows DLL.

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

Chris Marisic
A: 

Memory Management on Marshalling is a hard thing. You give very less information so i only can answer in general:

Te Interop marshaller use CoTaskMemFree and CoTaskMemAlloc to alloc memory. If your DLL allocates memory, and .NEt should free it (or vice versa) you have to use this functions. If the memory is allocated by new or malloc() and freed by delete or free() the library must provide some Cleanup() function to deal with this. To prevent the Marshaller from freeing memory, you must declare your functions with IntPtr as parameter / return value data type instead of using string or whatever else.

Consider this 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 must return a 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 freed automatically. You must call some kind of FreeMemory(IntPtr) function, which the library must provide.

Don't forget to read: .NET Default Marshaling Behavior

Thomas Maierhofer