繁体   English   中英

C ++二进制兼容的DLL POD类成员初始化导致崩溃

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM