我为mfc dll(C ++)编写了一个托管C ++ / CLI包装器,并在第二次调用dll后出现了一些访问冲突!
包装
// in .h
typedef CKeyManagerServerApp* (*KeyManagerInstance)(CCommonUtils *);
ManagedKeyInterface::ManagedKeyInterface()
{
HINSTANCE m_keyManagerLib = LoadLibrary("pathToDll");
KeyManagerInstance _createInstance = (KeyManagerInstance)GetProcAddress(m_keyManagerLib, "GetInstance");
// get native reader interface from managed reader interface
CCommonUtils *nativeReaderInterface = static_cast<CCommonUtils*>(readerInterface->nativeReaderInterface.ToPointer());
CKeyManagerServerApp *m_keyManagerApp = (_createInstance)(nativeReaderInterface );
}
ManagedKeyInterface::~ManagedKeyInterface()
{
try
{
DestroyKeyManagerInstance _destroyInstance = (DestroyKeyManagerInstance)GetProcAddress(m_keyManagerLib, "DestroyInstance");
(_destroyInstance)(m_keyManagerApp);
FreeLibrary(m_keyManagerLib);
}
catch(System::Exception ^e)
{
FreeLibrary(m_keyManagerLib);
}
}
NATIVE MFC CLASS
extern "C" _declspec(dllexport) CKeyManagerServerApp* GetInstance(CCommonUtils *readerInterface)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return new CKeyManagerServerApp(readerInterface);
}
extern "C" _declspec(dllexport) void DestroyInstance(CKeyManagerServerApp *ptr)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
delete ptr;
}
// constructor
CKeyManagerServerApp::CKeyManagerServerApp(CCommonUtils *readerInterface)
{
m_log = new Logging(loggingFilePath); // <--- ERROR at second call
// reader interface object for communication
m_readerComm = new ReaderCommunication(readerInterface, m_log);
m_smartmaskcmds = new CSmartMaskCmds(m_readerComm, m_log);
readerInterface = NULL;
}
// destructor
CKeyManagerServerApp::~CKeyManagerServerApp()
{
// destruct objects
delete m_smartmaskcmds;
delete m_readerComm;
delete m_log;
}
在ReaderCommunication和CSmartMaskCmds constr中。该对象只会被分配!
在C#程序的第一个运行时(加载带有添加引用的包装器)一切正常,但是当我再次启动时,我得到:
TestKeyManagerApp.exe中0x76f85b57的第一次机会异常:0xC0000005:访问冲突读取位置0xdddddddd。 TestKeyManagerApp.exe中的第一次机会异常0x75169617:Microsoft C ++异常:内存位置0x0024e820处的CMemoryException ..
当我调用m_log = new Logging(loggingFilePath)
时似乎析构函数不能正常工作!?
任何想法!! ??
谢谢!
答案 0 :(得分:2)
当您看到值0xdddddddd
时,表示some pointer was deleted(VC将在调试版本上设置该值以帮助您识别这些情况)。您没有告诉我们loggingFilePath
以及Logging
是如何实现的,但我的猜测是loggingFilePath
在某个时候被删除,Logging
尝试访问其值或构造函数(或初始化列表)中的虚函数。
这也可以解释析构函数中的崩溃 - 你正在删除m_log
,它可能包含从loggingFilePath
获得的非法指针。当你再次尝试使用它时,你会遇到同样的崩溃。
答案 1 :(得分:0)
当我调用m_log = new Logging(loggingFilePath)
时
幕后发生了什么?找出崩溃的确切位置。如果使用C#,则启用非托管调试。我想问题出在Logging
构造函数下。