C++/CLI System.AccessViolation在托管类中调用非托管函数时出现异常
C++/CLI System.AccessViolationException when calling unmanaged function in managed class
我在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)();
}
现在,如果我调试它,我会收到一条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.
错误消息。
难道,调用约定有问题吗?
谢谢
本机部分设置错误:
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.
此外,我的 Visual Studio 2010 在调试回调时崩溃(在我的 C++/CLI 包装器中(。如果我等待的时间足够长,它会引发以下异常:
Access violation reading location 0xfffffffffffffff8.
相关文章:
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 通过引用从 c++ 函数异常返回对象是否安全
- 智能指针和构造函数异常
- 构造函数C++异常说明符
- boost::archive::text_iarchive构造函数异常
- C++堆栈对象的构造函数异常处理
- 默认构造函数C++异常不会引发吗?
- 重写std的析构函数:异常
- 将向量作为参数(C++)传递时,没有匹配函数异常
- 当函数中静态变量的构造函数异常终止时会发生什么
- 如何:捕获输入函数异常的可变包装函数
- 在c++中,如果基类构造函数异常,则构造函数和析构函数的顺序可以是这样
- noexcept(false)析构函数覆盖所有特殊成员函数'异常规范
- c++重载函数异常规范
- c++ RAII析构函数异常
- 如何捕获构造函数异常
- C++构造函数异常处理
- 捕获构造函数异常的RAII方法
- C++析构函数异常
- Std::unique_ptr::reset和构造函数异常