如何使用 C 的内部 C++ 类类型?

How to use internal c++ class types from C?

本文关键字:类型 C++ 内部 何使用      更新时间:2023-10-16

我有一个C++类MyClass声明一个公共枚举类型MyEnum,我想在C文件中使用该枚举。我该怎么做?

我试图在C++文件中声明我的函数,然后将所有内容都放在extern "C",但遗憾的是我正在使用big_hugly_include.h中定义的一些函数,并且此标头不喜欢包含在external "C"(它给了我一个template with C linkage错误)。

我不能(不想)更改此包含,我需要它,因为它定义了my_function_from_big_include.我被困了吗?


my_class_definition.h

class MyClass
{
public:
// I would like to keep it that way as it is mainly used in C++ files
typedef enum
{
MY_ENUM_0,
MY_ENUM_1,
MY_ENUM_2
} MyEnum;
};

尝试 1 :my_c_function_definition.c

#include "my_class_definition.h"
// I cannot remove this header
#include "big_hugly_include.h"
// foo is called in other C files
void foo()
{
// I need to call this function with the enum from the C++ class
// This doesn't work (class name scope does not exist in C)
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}

尝试 2 :my_c_function_definition.cpp

#include "my_class_definition.h"
extern "C"
{
// Error template with C linkage
#include "big_hugly_include.h"
// foo is called in other C files
void foo()
{
// That would be ideal
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}
// end of extern "C"
}

为响应@artcorpse而编辑

尝试 3 :my_c_function_definition.cpp

#include "my_class_definition.h"
// Error multiple definition of [...]
// Error undefined reference to [...]
#include "big_hugly_include.h"
extern "C"
{
// foo is called in other C files
void foo()
{
// That would be ideal
my_function_from_big_include(MyClass::MyEnum::MY_ENUM_0);
}
// end of extern "C"
}
我想

在C文件中使用该枚举。我该怎么做?

C++中的枚举概念源自 C,所以你唯一要做的就是将定义这个枚举与 C 不知道的纯 cpp API 隔离开来(记住名称重整,见下文)。

由于 C 不知道类/结构枚举,因此您不能使用它们。您必须定义全局范围枚举或创建此类枚举,该枚举将映射C++特定枚举。

因此,在共享 API 应位于的位置创建单独的头文件。做这样的事情:

// shared C, C++ header
#ifdef __cplusplus
extern "C" 
{
#endif
enum YourMagicEnum {
YourMagicEnumAValue,
YourMagicEnumBValue,
YourMagicEnumCValue,
};
void someFunction(YourMagicEnum x);
#ifdef __cplusplus
} // extern "C"
#endif

现在,只有函数禁用名称重整才需要此extern "C"(C++您可以执行函数重载,因此编译器生成包含参数类型信息的名称)。

在定义此类函数时,它还应该在该定义前面有extern "C"

请记住,在该标头中只能放置特定于 C 的特性和功能。

还要记住,VLA(可变长度数组)是 C 标准,但不C++标准(大多数编译器支持 VLA for C++)。

有关更多信息,请参阅此页面。

您的 Try2 非常接近解决方案。尝试将包含移动到外部"C"之外。 我通常只单独标记每个函数:

extern "C" void foo() 
{
...
}

这样做的好处是只将一个符号导出为 C 符号,而不是尝试转换所有符号。