我有一些 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/