c/c++互动和枚举

发布于 2025-02-07 03:25:55 字数 760 浏览 1 评论 0原文

我希望通过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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无敌元气妹 2025-02-14 03:25:56

C码直接使用C ++枚举。
如评论中所述,将枚举放在代码的C部分中,并将其导入C ++代码。但这将枚举插入全球名称空间。

如果您不想要它,还有其他不错的选择:

  • 在C和C ++代码中编写枚举。要执行平等,请使用一些静态断言。 (示例(enum class而不是普通枚举)
  • 写一个宏,因此PrePocersor为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:

  • Write the enum in the c and c++ code. To enforce there are equal, use some static asserts. (example (enum class instead of plain enum))
  • Write a macro so the pre-processor generates two enums for the c++ and c code with the same entries. This adds the possibility of namespaces. (example)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文