c/c++互动和枚举
我希望通过C函数公开C ++库,以便可以从C和其他可以导入C代码的语言中使用它。我将在C函数调用中包装的一些C ++方法采用enum
值来自C ++库中类似类型的类型:
enum FooFromCPP { // From C++
x = 0,
y,
z
}
我的问题是我需要一种使此枚举可用的方法C代码,但我看不到一种方法除了在标题中重新创建等效枚举外,我将从C中导入的枚举:
enum FooC { // C equivalent
x_c = 0,
y_c,
z_c
}
我的第一个问题是,如果我在库的C ++标题中定义了枚举,则使用,是否有一种更简单的方法可以使其可用于我的C代码而不是复制它?我认为不仅会导入包含它的标头,因为它还包含不兼容的C ++类型。
我的第二个问题是,我想知道C中枚举的内存布局是否与相应的C ++枚举兼容?将C枚举施放给C ++的一个人从我的C warper中调用C ++方法是有效的吗?
void bar(MyClassPointer* ptr, FooC fooEnum) {
((MyClassCPP*)ptr).bar((FooFromCPP)fooEnum);
}
I wish to expose a C++ library through C functions so that it can be used from C and other languages that can import C code. Some of the C++ methods I will wrap in C function calls take enum
values coming from types defined like this in the C++ library:
enum FooFromCPP { // From C++
x = 0,
y,
z
}
The problem I have is that I need a way to make this enum available to the C code, but I don't see a way to do this apart from recreating an equivalent enum in the header I will import from C:
enum FooC { // C equivalent
x_c = 0,
y_c,
z_c
}
My first question is, if I have an enum defined in a C++ header of a library I'm using, would there be an easier way to make it available to my C code instead of copying it? I don't think just importing the header that contains it would work since it also contains C++ types that aren't C compatible.
My second question is that I would like to know if the memory layout of the enum in C will be compatible with the corresponding C++ enum? Is it valid to cast the C enum to the C++ one to call the C++ method from my C warper like this?
void bar(MyClassPointer* ptr, FooC fooEnum) {
((MyClassCPP*)ptr).bar((FooFromCPP)fooEnum);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C码直接使用C ++枚举。
如评论中所述,将枚举放在代码的C部分中,并将其导入C ++代码。但这将枚举插入全球名称空间。
如果您不想要它,还有其他不错的选择:
There is no option to use the c++ enum directly in your c code.
As stated in the comments, put the enum in the c part of your code and import it in the c++ code. But this inserts the enum into the global namespace.
If you don't want that, there are other less nice options: