在DLL中,C 静态矢量会失去元素

c++ static vector loses elements when in DLL

本文关键字:失去 元素 静态 DLL      更新时间:2023-10-16

,因此我有一个主程序,该程序引用了DLL(在单独的解决方案中(。这是设计代码:

//.h of DLL
#ifdef DLL_PREPRO
    #define DLL_LINK __declspec(dllexport)
#else
    #define DLL_LINK __declspec(dllimport)
#endif
enum MyID
{
    //values here....
}
DLL_LINK class MyCustomClass
{
public:
    MyID id;
    LPCTSTR lpszApp;
    LPCTSTR lpszKey;
    LPCTSTR lpszDefault;
    CString& strData;
}
static vector<MyCustomClass> m_customClass; //the vector in question
DLL_LINK void InitTables();
//I have other custom classes that has almost similar structure to this, and with their corresponding vector
//on the .cpp is the implementation of function InitTables() that is called by the EXE side wherein I am doing some processing on the vectors
//.cpp on the EXE side
void AddCustomClass(MyCustomClass c)
{
    (&m_customClass)->push_back(c);
}
//I have another method here who populates the vector by calling AddCustomClass repeatedly

我的问题是,在调试期间,在exe侧,我看到矢量被填充了(我是通过'添加到每个向量的"添加"来做到这一点(,但是当我逐步浏览(f10(到inttables函数在DLL侧,所有向量现在都包含0个元素。顺便说一句,我将DLL的CPP文件拖到EXE解决方案上,以便设置断点。由于访问那些具有空元素的向量会出现错误,因此我暂时将返回放在inttables((函数的顶部。然后,当我再次f10 返回到EXE解决方案中的下一行时,所有向量现在都将其元素返回

所以我的问题是,设计/源代码有什么问题,该如何纠正?谢谢!

问题是您在标题文件中使用了键入静态:

static vector<MyCustomClass> m_customClass; //the vector in question

在此上下文中,静态表示:此符号仅在当前单元中可见。因此,包含此标头文件的每个.cpp文件都有此全局变量的实例!实际上,您可以拥有此变量的10个实例。

可能您想要这样的东西:

extern DLL_LINK vector<MyCustomClass> m_customClass;

和相应的.cpp文件只需添加:

vector<MyCustomClass> m_customClass;

命名空间范围变量上的 static指定符给出了变量 internal 链接。简而言之,这意味着每个.cpp文件将具有自己的变量的副本。显然不是你想要的。如果您希望在DLL中定义变量,但可以从EXE访问,则实际上必须是extern(并导出(,而不是static