在托管类中调用非托管函数时,C ++ / CLI System.AccessViolationException [英] C++/CLI System.AccessViolationException when calling unmanaged function in managed class
问题描述
我在C ++中有一个本机回调函数,让我们这样说:
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);
}
好了,所以现在我调用了托管函数,并给了该函数一个本地c ++功能。
让我们看一下托管代码:
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)();
}
现在,如果我对此进行调试,则会得到 .dll中发生类型为System.AccessViolationException的未处理异常。其他信息:试图读取或写入受保护的内存。这表示其他内存已损坏。
错误消息。
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.
调用约定有问题吗?
谢谢
推荐答案
本机部分设置错误:
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);
}
回调函数有效,但是在本地主函数中仍然出现错误:
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.
此外,调试回调(在C ++ / CLI包装器中)时,Visual Studio 2010崩溃。如果我等待了足够长的时间,它将引发以下异常:
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 ++ / CLI System.AccessViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!