C++/CLI System.AccessViolationException when calli

2020-04-16 02:13发布

问题:

I have a native callback function in C++, let's say something like this:

void ::CallbackFunction(void)
{
  // Do nothing
}

Now I have another native function:

void ::SomeNativeFunction(void)
{
  m_callback = std::tr1::bind(&::CallbackFunction, m_Tcy); // save in m_callback | m_Tcy is the class where CallbackFunction exists
  m_Tcy->SomeManagedFunction(m_callback);
}

Alright, so now I called a managed function and gave this function a native c++ function. Let's look into the managed code:

// This won't work
// typedef std::tr1::function<void __stdcall ()>* callback_function;
typedef std::tr1::function<void()>* callback_function;

callback_function m_nativCallback;

void ::SomeManagedFunction(callback_function callback)
{
  m_nativCallback = callback;
  // Does some stuff that triggers SomeManagedCallback
}

void ::SomeManagedCallback(IAsyncResult^ ar)
{
  (*m_nativCallback)();
}

Now, if I debug this, I get a An unhandled exception of type System.AccessViolationException occurred in .dll Additional information: An attempt was made to read or write in the protected memory. This is an indication that other memory is corrupted. error message.

Can it be, that something is wrong with the calling convention?

Thanks

回答1:

The native part was set up wrong:

void ::SomeNativeFunction(void)
{
  m_callback = std::tr1::bind(&::CallbackFunction, m_Tcy); // save in m_callback | m_Tcy is the class where CallbackFunction exists
  //this won't work
  m_Tcy->SomeManagedFunction(m_callback);
}

This worked for me:

void ::SomeNativeFunction(void)
    {
      m_callback = std::tr1::bind(&::CallbackFunction, m_Tcy); // save in m_callback | m_Tcy is the class where CallbackFunction exists
      //this works, even tho the debugger dies on me when I try to debug this
      m_Tcy->SomeManagedFunction(&m_callback);
    }

The callback stuff works, but still getting a error in the native main though:

First-chance exception at 0x00007ffb2b59dd60 in *.exe: 0xC0000005: Access violation at location 0x00007ffb2b59dd60.
Unhandled exception at 0x00007ffb2b59dd60 in *.exe: 0xC000041D: Exception during a user callback.

Also, my visual studio 2010 crashes when debugging the callback (in my C++/CLI wrapper). If I wait long enough, it throws the following exceptions:

Access violation reading location 0xfffffffffffffff8.


标签: c++ c++-cli