MFC dll (c++ /CLI封装)中的访问冲突始于c#程序

本文关键字:访问冲突 程序 dll c++ 封装 CLI MFC | 更新日期: 2023-09-27 18:02:18

我已经为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和csmartmaskcmd构造。对象只会被分配!

在c#程序的第一次运行时(用add引用加载包装器)一切都工作正常,但当我再次启动它时,我得到:

在TestKeyManagerApp.exe中的0x76f85b57第一次机会异常:0xC0000005:访问违反读取位置0xdddddddd。第一次机会异常在0x75169617在TestKeyManagerApp.exe: Microsoft c++异常:CMemoryException在内存位置0x0024e820..

当我调用m_log = new Logging(loggingFilePath)

似乎析构函数不能正常工作!?

任何想法! ! ? ?

谢谢!

MFC dll (c++ /CLI封装)中的访问冲突始于c#程序

当您看到值0xdddddddd时,这意味着某些指针被删除(VC将在调试构建时设置该值以帮助您识别这些情况)。你没有告诉我们什么是loggingFilePathLogging是如何实现的,但我的猜测是loggingFilePath在某个时候被删除了,Logging试图访问它的值或构造函数(或初始化列表)中的虚函数。

这也可以解释析构函数中的崩溃——你正在删除m_log,它可能持有从loggingFilePath获得的非法指针。当你试图再次使用它时,你会遇到同样的崩溃。

当我调用m_log = new Logging(loggingFilePath)

幕后发生了什么?找出它到底在哪里崩溃的。如果使用c#,请启用非托管调试。我猜问题是在Logging构造器下。