在内存中为多个文件保存构造的静态数组c ++

holding constructed static arrays in memory for multiple files c++

我有一些数组需要在我的程序运行期间保存在内存中。这些数组被不同的文件用作查找引用,所以我想我应该制作一个 DLL 来保存它们。

我似乎 运行 遇到的主要问题是文件必须在程序开始时构建。每个数组包含几千个值,未来可能包含数百万个值,因此硬编码数组不是一种选择。

这是我最好的尝试:

首先,我制作了Dll头文件。我阅读了有关制作静态构造函数的信息,这就是我在这里尝试保存数组的方法。我只将导出放在 NumCalc class(正确吗?)。

// 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

我之前的尝试没有使用静态构造函数。没有 class 数组。 NumCalc 是唯一 class 包含

static TABLESDLL_API const int* arr

和私有函数

static const int* SetNums().

这产生了 LNK2001 compiler error when run in the TestTablesDll

我很确定函数在编译时未 运行ning 存在问题,未定义 arr 变量。

我该怎么做?

TablesDll.h 中你也应该把 TABLESDLL_API 放到 Arrays class 中。否则您将无法使用 NumCalc 中依赖于 Arrays.

的部分

你也应该在 TablesDll.cpp 中有这个 Arrays NumCalc::arrays; 即使 Arrays 是空的 class - arrays 必须在某处定义(而不是刚刚在 class 定义中声明。

编辑:还有更多问题。

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"