如何使用 C 的内部 C++ 类类型?
How to use internal c++ class types from C?
我有一个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 符号,而不是尝试转换所有符号。
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 类中的字符串不命名类型