Search code examples
c++multithreadingunmanagedmsdnmanaged

Windows Forms: Unmanaged code calls an internal thread that causes 'Access violation'


So I'm using some native code (only access to the DLLs; no source code) that causes my program to crash. Essentially, I try to connect to a server which initially connects fine. There is a connection object provided by the API which is used as the abstraction for the programmer.

First I pass two (marshaled) callback functions back to the connection object. One is an event call-back, and the other an error call-back. Then, I use a "connection" function to start the connection. This creates an internal thread to handle the connection. It invokes the event callback and notifies me that it connected with no issues.

The problem occurs when the connection fails (which it does after a timeout), the error CB function gets called and after it is done running, I get the (0xc0000005) 'Access violation' error. I'm assuming it's the internal thread that's causing the issue, since any internal-thread-creating native C function within the API causes an access violation. How can I handle this? Also I'm using managed C++ if that helps any. Thanks!


Solution

  • Well if anyone was wondering, it has to do with the GC. By pinning down the variables the native C code and managed code uses via GCAlloc and GCHandleType, and calling the native C code with extern "C", I managed to fix most errors that occurred. It also would be easier if all code that referenced the API code would be referenced outside of managed code - eg a source file that uses #pragma unmanaged.

    Moreover, MFC might be an easier choice rather than Windows Forms when making a GUI that deals with a lot of unmanaged code... unless you want your GUI to do some more complicated things :)