我有一个C++中的类,我想从中制作一个共享库
,并在C
或其他语言中使用。 这是我要从中创建库的类:
getInfo.h
#ifndef GETINFO_H
#define GETINFO_H
#include "info.h"
char* getMaximumSpeedCpu();
char* getCoreNumbers();
#endif
getInfo.cpp:
#include <iostream>
#include "getinfo.h"
using namespace Morsa::Prd::SMC::SL;
char* getMaximumSpeedCpu()
{
info *inf = new info;
std::string str = inf->maximumSpeedCpu();
char* maxspeed = new char[str.length()+1];
strcpy(maxspeed, str.c_str());
free(inf);
return maxspeed;
}
char* getCoreNumbers()
{
info *inf = new info;
std::string corenum = inf->coreNumbers();
char* num = new char[corenum.length()+1];
strcpy(num, corenum.c_str());
free(inf);
return num;
}
这是我的包装类(smc.h):
#ifndef SMC_H
#define SMC_H
#include "getinfo.h"
#ifdef __cplusplus
extern "C"
{
#endif
//void smc_destroy(ctestsmc *a);
char* smc_getMaximumSpeedCpu();
char* smc_getCoreNumbers();
#ifdef __cplusplus
}
#endif
#endif // SMC_H
SMC.cpp:
#include "smc.h"
char *smc_getMaximumSpeedCpu()
{
char* c = getMaximumSpeedCpu();
return c;
}
char *smc_getCoreNumbers()
{
char* c = getCoreNumbers();
return c;
}
我从smc.cpp创建了一个共享库
,现在我想在例如C
代码中使用我的库。
在不包括任何头文件的情况下,我应该如何执行此操作? 每当我包含smc的头文件时,我的c
代码就不知道我在getInfo.h中使用过的库,比如fstream
。
您只能从C世界访问用C编写的函数。每当从C调用C++代码时,您必须通过包装函数,在您的例子中是SMC_*
函数。
现在,请注意包装器函数的声明(位于包装器的头文件smc.h
中)不需要包含getInfo.hpp
。 这是关键的洞察力。 包装器的头仅仅告诉包含它的任何C程序,参数的类型和SMC_*
函数的返回值。 标题必须粘在C上。
例如,请参见下面的图像。 函数foo
和bar
在wrapper.h
文件中声明,该文件只包含其他C头。 wrapper.cpp
文件实际上实现了包装器,并使用了C++世界中的其他东西(如STL或其他类),其中包括所需的C++头。
在您的示例中,smc.cpp
将包括getInfo.hpp
,而不是smc.h
。
但是,这些包装器函数的定义需要知道它正在包装的C++函数的类型。 因此,smc.cpp
将包括getInfo.h
。 此外,由于该文件将由C++编译器编译,因此它将理解包含的头中对C++STL的任何引用。