From: Jef D. <jef...@ho...> - 2008-07-22 10:39:14
|
I'm building a DLL with mingw32. It works perfect when used in a C/C++ application, but something goes wrong when used in a C# project. Ordinary functions work, but with callback functions it starts to go wrong. I'm able to reproduce the problem with the following code sample for the DLL: typedef void (*callback_t) (unsigned int size, void *userdata); void myfunction (callback_t callback, void *userdata) { for (unsigned int i = 0; i < 100; ++i) { printf ("iteration %u\n", i); if (callback) callback (i, userdata); } } Now I create a simple C# console project (with MSVC), and try to use this DLL with the following code: [DllImport("mydll.dll")] static extern void myfunction (callback_t callback, IntPtr userdata); static void test_callback (UInt32 size, IntPtr userdata) { Console.WriteLine (size); } static void Main(string[] args) { callback_t mycallback = new callback_t (test_callback); myfunction (mycallback, IntPtr.Zero); } It runs fine for the first few iterations, but than something goes wrong. I get this output: iteration 0 0 iteration 1 1 iteration 2 2 iteration 3 3 iteration 4 0 iteration 1 1697911994 Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at test.Class1.myfunction(callback_t callback, IntPtr userdata) at test.Class1.Main(String[] args) Any idea what is going wrong here? If I compile the DLL with MSVC, everything is fine. |