呼叫DLL開啟執行緒的問題
阿新 • • 發佈:2020-12-17
錯誤的編寫方式:(注意用感嘆號夾起來的兩行)在::FreeLibrary(hPro);這一行程式碼執行之後,dll裡面的分配的記憶體空間就會全部被釋放掉,所以會報“幀不在模組之中”,“記憶體訪問錯誤”之類的錯誤。
void CMFCApplication2Dlg::OnBnClickedOk() { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! HINSTANCE hPro = ::LoadLibrary("MFCLibrary1.dll");//載入一個自己寫的DLL,提供了一 //getCFindFile用於獲取一個類指 //針; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (hPro == NULL) { return ; } else { typedef MyCFindFile* (*MENU_EXECUTE)(); MENU_EXECUTE getCFindFile = NULL; getCFindFile = (MENU_EXECUTE)::GetProcAddress(hPro, "getCFindFile");//MenuExecute 函式名字 if (getCFindFile) { MyCFindFile * pItem = getCFindFile(); CString s; GetDlgItemText(IDC_EDIT4,s); s.Format(_T("%s"), s); std::string strStr; strStr = s.GetBuffer(0); HWND hdlg = GetSafeHwnd(); pItem->funcFindFile(strStr, hdlg, 2); //pItem->m_hMainDlg = GetSafeHwnd();//把當前主對話方塊的視窗控制代碼傳過去,這樣就可以線上程函式中使用 //m_ResultList.DeleteAllItems();//清空上一次執行完之後的資訊 //std::string strStr; //strStr = pItem->m_PathFind.GetBuffer(0); //funcFindFile(strStr, pItem->m_hMainDlg); } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ::FreeLibrary(hPro); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } return; }
正確的寫法:
1,將HINSTANCE hPro;新增到類成員變數之中
2,將FreeLibrary(hPro);函式放到MFC退出按鈕裡面,反正要保證在使用完hpro之前不要釋放掉,也可以直接用靜態載入