编程语言
首页 > 编程语言> > 当在托管类中调用非托管函数时,C/C++LI System.AccessViolationException

当在托管类中调用非托管函数时,C/C++LI System.AccessViolationException

作者:互联网

我在C中有一个本机回调函数,我们可以这样说:

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

现在,我还有另一个本机功能:

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);
}

好了,现在我调用了托管函数,并为该函数提供了本机c函数.
让我们看一下托管代码:

// 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)();
}

现在,如果我对此进行调试,则会在.dll中收到类型为System.AccessViolationException的未处理异常.其他信息:试图读取或写入受保护的内存.这表明其他内存已损坏.错误信息.

调用约定有问题吗?

谢谢

解决方法:

本机部分设置错误:

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);
}

这为我工作:

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);
    }

回调的东西可以用,但是在本地主目录中仍然会出现错误:

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.

另外,调试回调(在C/C++LI包装器中)时,Visual Studio 2010崩溃.如果我等待足够长的时间,它将引发以下异常:

Access violation reading location 0xfffffffffffffff8.

标签:c,c-cli
来源: https://codeday.me/bug/20191012/1896939.html