在DLL中,C 静态矢量会失去元素
c++ static vector loses elements when in DLL
,因此我有一个主程序,该程序引用了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
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在DLL中,C 静态矢量会失去元素
- 如何防止 XAML UI 元素在失去焦点时修改其外观