c++ - 在托管类中调用非托管函数时出现 C++/CLI 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)();
}
现在,如果我调试它,我会收到一条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.
推荐阅读
- javascript - 使用 canvas + css 动画构建棋盘游戏
- python - 从列表中选择要放入图表的值
- php - PHP preg_split 添加了一个无法被 array_filter 清除的空白数组键,因为其中有一个“空格”
- bash - Linux在文本文件中打印交替的2行
- c++ - 有没有办法通过模板参数自动解析重载方法?
- php - 如何将 URL 中的视频分享到社交媒体 - 自动播放
- php - 在 Laravel 集合中搜索值
- jquery - 如何在sql查询中列出订单?
- java - 读取文件,将其存储在数组列表中,遍历数组,打印数据
- python - 如何使用 selenium python 点击页面链接