C++/CLI System.AccessViolationException when calling unmanaged function in managed class

a 夏天 提交于 2019-12-02 05:06:59

问题


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.


来源:https://stackoverflow.com/questions/52929912/c-cli-system-accessviolationexception-when-calling-unmanaged-function-in-manag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!