我有一些数组需要在我的程序运行期间保存在内存中。这些数组用作不同文件的查找引用,所以我想我应该制作一个 DLL 来保存它们。
我似乎遇到的主要问题是文件必须在程序开始时构建。每个数组包含几千个值, future 可能包含数百万个值,因此对数组进行硬编码不是一种选择。
这是我最好的尝试:
首先,我制作了Dll头文件。我阅读了有关制作静态构造函数的信息,这就是我在这里尝试保存数组的方法。我只将导出放在 NumCalc 类上(正确吗?)。
// TablesDll.h
#ifndef TABLESDLL_EXPORTS
#define TABLESDLL_EXPORTS
#ifdef TABLESDLL_EXPORTS
#define TABLESDLL_API __declspec(dllexport)
#else
#define TABLESDLL_API __declspec(dllimport)
#endif
namespace tables
{
class Arrays
{
public:
static const int* arr;
private:
static int* SetNums();
};
class TABLESDLL_API NumCalc
{
public:
static Arrays arrays;
};
}
#endif
现在是定义:
// TablesDll.cpp
#include "stdafx.h"
#include "TablesDll.h"
#include <stdexcept> (<- I don't know why this is here...)
namespace tables
{
const int* Arrays::arr = SetNums();
int* Arrays::SetNums()
{
int* arr= new int[2000];
/* set the numbers*/
return arr;
}
}
它编译得很好。我将这些文件粘贴到测试程序中:
// TestTablesDll
#include "stdafx.h"
#include "TablesDll.h"
using namespace tables;
int _tmain(int argc, _TCHAR* argv[])
{
for(int i=0; i<299; i++)
printf("arr[%i] = %d/n", i, NumCalc::arrays::arr[i]);
return 0;
}
不幸的是,这甚至不能编译。
error C3083: 'arrays': the symbol to the left of a '::' must be a type
我之前的尝试没有使用静态构造函数。没有数组类。 NumCalc 是唯一包含
static TABLESDLL_API const int* arr
和私有(private)函数
static const int* SetNums().
这在 TestTablesDll 中运行时产生了 LNK2001 编译器错误
我很确定这个函数在编译时没有运行,导致 arr 变量未定义。
我该怎么做?
最佳答案
在 TablesDll.h
中,您也应该将 TABLESDLL_API
放入 Arrays
类。否则,您将无法使用 NumCalc
中依赖于 Arrays
的部分。
此外,即使 Arrays
是一个空类,您也应该在 TablesDll.cpp
中包含此 Arrays NumCalc::arrays;
- 数组
必须在某处定义(而不仅仅是在类定义中声明)。
编辑:还有更多问题。
arr
应该像这样访问:NumCalc::arrays.arr
- 使用 .
而不是使用 ::
此外, header 总是导出符号,因为您定义了 TABLESDLL_EXPORTS
,然后立即检查它是否已定义。应该是这样的:
#ifndef TABLESDLL_HEADER_GUARD
#define TABLESDLL_HEADER_GUARD
#ifdef TABLESDLL_EXPORTS
#define TABLESDLL_API __declspec(dllexport)
#else
#define TABLESDLL_API __declspec(dllimport)
#endif
并且在 TablesDll.cpp
中,您应该在包含 header 之前定义 TABLESDLL_EXPORTS
- 这样只有 dll 导出符号和可执行文件导入他们。像这样:
#define TABLESDLL_EXPORTS
#include "TablesDll.h"
关于c++ - 在内存中为多个文件保存构造的静态数组c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30124045/