[英]C++ binary compatible dll POD class member initialization causes crash
我正在嘗試使用mingw構建的dll中使編譯器間兼容的類可以在Windows VS應用程序中使用。 我的問題是,當從VS程序調用函數時,我的類在嘗試初始化成員變量時崩潰。 使用STL或在同一函數中使用局部變量可以很好地工作。
ConsoleApplication2.exe中0x6BEC19FE(test.dll)處未處理的異常:0xC0000005:訪問沖突寫入位置0x154EB01E。
簡單演示:
dll代碼
#include <iostream>
class Tester
{
public:
virtual void test() = 0;
};
class TesterImp : public Tester
{
public:
TesterImp(){}
~TesterImp(){}
virtual void test() {
int test = 5; // fine
m_test = 5; // access violation
}
private:
int m_test;
};
extern "C"
{
__declspec (dllexport) Tester* Create()
{
return new TesterImp();
}
}
加載dll並調用測試函數的主程序:
#include <iostream>
#include <Windows.h>
class Tester
{
public:
virtual void test() = 0;
};
typedef Tester* (*createPtr)();
int main(int argc, const char **argv, char * const *envp) {
HINSTANCE hGetProcIDDLL = LoadLibraryA("test.dll");
if (hGetProcIDDLL == NULL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
createPtr ctr = (createPtr)GetProcAddress(hGetProcIDDLL, "Create");
if (!ctr) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
std::cout << "dll loading success!" << std::endl;
Tester* testf = ctr();
std::cout << "Got test class" << std::endl;
testf->test(); // crash if the member variable is referenced, fine otherwise with local variable initialization or STL use inside the function
std::cout << "Running dll functions success!" << std::endl;
return 0;
}
使用VS2012在調試模式下編譯主程序,並且使用mingw的g ++構建dll-
g ++ -shared -o test.dll test.cpp
有人可以幫我解釋一下這種行為嗎?
謝謝。
您可能正在使用較舊版本的MinGW。 直到4.7.0(我認為),MinGW在堆棧上傳遞了this
指針,這與MSVC在ecx
中傳遞this
指針的thiscall
約定不同。
從4.7.0開始,MinGW使用與MSVC相同的thiscall
調用約定。
我還可以得到例如TesterImp::test()
函數從MSVC被稱為成功標志着這兩個Tester::test()
和TesterImp::test()
在test.cpp
與__attribute__((thiscall))
屬性。 這與MinGW 4.6.2配合使用,如果不使用該屬性,將導致崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.