c++ - 声明使用 C 代码的 c++ 类的多个实例

标签 c++ c

我有一些 C 库,我希望能够将它们包装在一个 C++ 类中并创建多个完全独立的实例。我试过这样做,但问题是 C 代码中的变量只是在所有 C++ 类实例之间共享。

我试过制作一个静态库并引用它但无济于事。有谁知道如何做到这一点?

下面的代码示例:我有一个名为 CCodeTest 的 C 文件,它只是将一些数字添加到内存中的一些变量中。我在 MathFuncsLib.cpp 中有一个类,它使用了这个。我希望能够创建 MyMathFuncs 类的多个实例,并使 C 代码中的变量独立

CCodeTest.h

#ifndef C_CODE_TEST_H
#define C_CODE_TEST_H

extern int aiExternIntArray[3];

#if defined(__cplusplus)
  extern "C" {
#endif

#define CCODE_COUNT  3

void CCodeTest_AddToIntArray(int iIndex_);
int CCodeTest_GetInternInt(int iIndex_);
int CCodeTest_GetExternInt(int iIndex_);


#if defined(__cplusplus)
   }
#endif
#endif   //defined(C_CODE_TEST_H)

数学函数库.cpp

#include "MathFuncsLib.h"
#include "CCodeTest.h"

using namespace std;

namespace MathFuncs
{
    void MyMathFuncs::Add(int iNum_)
    {
       CCodeTest_AddToIntArray(iNum_);
    }

    void MyMathFuncs::Print(void)
    {
       for(int i = 0; i < CCODE_COUNT; i++)
       {
          printf("Intern Index %i: %i\n", i, CCodeTest_GetInternInt(i));
          printf("Extern Index %i: %i\n", i, CCodeTest_GetExternInt(i));
       }
    }
}

如有任何帮助,我们将不胜感激!

最佳答案

你有一个名为 aiExternIntArray 的全局变量。那就是问题所在。 C++ 类的每个实例都对该数组进行操作。

您需要做的是创建一个包含 int[3] 的 struct,以便您可以创建此类型的单独实例。

typedef struct
{
    int aiIntArray[3];
} CodeTestStruct;

void CCodeTest_AddToIntArray(CodeTestStruct* ct, int iIndex_);
int CCodeTest_GetInternInt(CodeTestStruct* ct, int iIndex_);
int CCodeTest_GetExternInt(CodeTestStruct* ct, int iIndex_);

在 C++ 中,您的类应该封装 CodeTestStruct

class CodeTestClass
{
public:
    void AddToIntArray(int iIndex_)
    {
        CCodeTest_AddToIntArray(&m_ct, iIndex_);
    }

    int GetInternInt(int iIndex_)
    {
        CCodeTest_GetInternInt(&m_ct, iIndex_);
    }

    int GetExternInt(int iIndex_)
    {
        CCodeTest_GetExternInt(&m_ct, iIndex_);
    }

private:
    CodeTestStruct m_ct;
};

关于c++ - 声明使用 C 代码的 c++ 类的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710324/

相关文章:

c++ - 零大小数组不适用于模板

c++ - C/C++ 编译器的最佳编译器警告级别?

c++ - 如果我将一个 TCanvas vector 传递给另一个类,为什么 ROOT 只允许我将一个 TCanvas vector 的最终元素设置为另一个 TCanvas vector ?

C const 数组元素不是真正的 const 吗?

c++ - 如何初始化可变长度的无符号字符数组?

c++ - 在 visual studio 中编码错误而不是 turbo C++ - C

c++ - 访问类中的结构成员,LinkedList Node

c++ - 二维数组C++的复制构造函数

java - 它适用于 Debian 5.0,但在 ubuntu 11.10 上会导致段错误

c - 在 C 中,仅在函数定义中而不是声明中添加 `const` 是否合法?