将构造的静态数组存储在多个文件中的内存中

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

本文关键字:文件 内存 存储 静态 数组      更新时间:2023-10-16

我有几个阵列在程序的持续时间内需要保存在内存中。这些数组被用作不同文件的查找引用,因此我认为我应该制作一个dll以将它们固定在中。

我似乎遇到的主要问题是必须在程序开始时构建文件。这些数组每个阵列都容纳数千个值,未来的值可能会容纳数百万美元,因此硬编码阵列不是一个选项。

这是我最好的尝试:

首先,我制作了DLL标头文件。我读到有关制作静态构造函数的信息,这就是我在这里试图在这里持有阵列的方法。我仅将导出放在数字类(正确?)。

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

和私人功能

static const int* SetNums().

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

我很确定该函数在编译时没有运行存在问题,而ARR变量不确定。

我该怎么做?

TablesDll.h中,您也应该将TABLESDLL_API放入Arrays类。否则,您将无法使用依赖于ArraysNumCalc的部分。

也应该在TablesDll.cpp中使用此Arrays NumCalc::arrays;,即使Arrays是一个空的类-arrays必须在某个地方定义(不仅在类定义中声明)。

编辑:还有更多问题。

arr应该像这样访问:NumCalc::arrays.arr-使用.,而不是::

此外,标题始终导出符号beacuse您定义 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中,您应该在包含标头之前定义TABLESDLL_EXPORTS - 以便仅 dll 导出符号和可执行文件可导入它们。这样:

#define TABLESDLL_EXPORTS
#include "TablesDll.h"