Visual Studio 2010和2012中STL容器的字节大小的差异

Ade*_*ost 2 c++ dll stl visual-studio visual-studio-2012

我正在与VS2010和VS2012的项目合作.

VS2010项目调用VS2012中的函数,反之亦然.这开始工作正常,但是当我还需要在两个项目之间共享变量时,我注意到变量似乎没有相同的内存对齐,并且每个项目都以不同的方式解释相同的内存地址.

更新:它似乎只发生在使用STL容器,其他结构和类不包含std ::工作正常.

为了说明问题,以下代码在不同的Visual Studio版本上运行时应该得到不同的结果.

#include <string>
#include <vector>

int main()
{
    int stringSize = sizeof(std::string);           // Yelds 32 on VS2010, 28 on VS2012
    int intVectorSize = sizeof(std::vector<int>);   // Yelds 20 on VS2010, 16 on VS2012

    return 0;
};
Run Code Online (Sandbox Code Playgroud)

不能将这两个项目更新到同一个版本,因为我有一些与每个版本相关的依赖项.

有没有人知道解决方案或绕过问题的方法?

我会尽快将这两个项目升级到VS2012编译器,但是现在我正在寻找一个快速而肮脏的解决方案,所以我可以相处工作.由于它似乎只发生在STL容器中,是否可以在所有项目中使用旧版本的库?或者是否有可能欺骗编译器?也许改变填充大小?

此外,std :: vector中的第一个元素看起来很好,只有向量中的后续元素似乎被扰乱.(见图.)

调试图像

在2010年和2012年编译的"main.cpp"中调试"Fetched"变量的图像.


有人希望我澄清变量的共享方式.

我们在VS2012编译模式下将第一个项目编译成DLL,然后尝试在VS2010中访问该项目.

这是重新创建问题的一些代码.如果您想亲自尝试,可以在此处下载完整的VS2012解决方案.

使用VS2012将此代码编译为DLL.

DllExport.h

#ifdef DLLHELL_EX
#define DLL_API __declspec(dllexport) 
#else
#define DLL_API __declspec(dllimport) 
#endif

#include <vector>
#include <string>

class DLL_API Foo
{
public:
    Foo();
    ~Foo();

    std::vector<std::string>* exposedMember;
};
Run Code Online (Sandbox Code Playgroud)

DllExport.cpp

#include "DllExport.h"

Foo::Foo()
{
    // Create member
    exposedMember = new std::vector<std::string>();

    // Fill member with juicy data
    for(int i=0; i<5; i++)
            exposedMember->push_back("Fishstick");
}

Foo::~Foo()
{
    // Clean up behind ourselves like good lil' programmers
    delete exposedMember;
}
Run Code Online (Sandbox Code Playgroud)

此代码使用DLL并使用VS2010进行编译.

main.cpp中

#include "DllExport.h"

int main()
{
    // Creating class from DLL
    Foo bar;

    // Fetching "exposedMember" from class
    std::vector<std::string>* member = bar.exposedMember;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用教程创建了DLL

Cor*_*son 10

绝对不应该混合来自不同版本的运行时的类型.即使它们的大小相同,它们也可能将变量存储在不同的位置,或者某些算法可能会略有变化.即使类型完全相同,不同的编译器也可能选择以不同的方式表示它们.

真的没有好办法做到这一点.C++不保证其标准库的实现不会改变,并且编译器似乎无法就ABI(即使在相同编译器的版本之间)达成一致,即使它们没有.在为其他人编写API时,大多数人选择只导出完全由他们控制的C类型.

  • _C++ _不是一种不稳定的语言.它没有标准_ABI_,也许这就是你的意思? (2认同)