提问者:小点点

包括一个在c程序中使用extern在c++中构建的头文件


我有一个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


共1个答案

匿名用户

您只能从C世界访问用C编写的函数。每当从C调用C++代码时,您必须通过包装函数,在您的例子中是SMC_*函数。

现在,请注意包装器函数的声明(位于包装器的头文件smc.h中)不需要包含getInfo.hpp。 这是关键的洞察力。 包装器的头仅仅告诉包含它的任何C程序,参数的类型和SMC_*函数的返回值。 标题必须粘在C上。

例如,请参见下面的图像。 函数foobarwrapper.h文件中声明,该文件只包含其他C头。 wrapper.cpp文件实际上实现了包装器,并使用了C++世界中的其他东西(如STL或其他类),其中包括所需的C++头。

在您的示例中,smc.cpp将包括getInfo.hpp,而不是smc.h

但是,这些包装器函数的定义需要知道它正在包装的C++函数的类型。 因此,smc.cpp将包括getInfo.h。 此外,由于该文件将由C++编译器编译,因此它将理解包含的头中对C++STL的任何引用。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(包括|c|程序|中|extern|c++|中|构建|头文件)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?