我可以使用' bool '类型或不透明指针指向导出到c的c++函数中的类吗?

Can I use `bool` type or opaque pointers to classes in a c++ function exported to c?

本文关键字:c++ 函数 bool 可以使 类型 我可以 指针 不透明 向导      更新时间:2023-10-16

我正在编写一个库的API。库本身将在c++中编写,但API将使用extern "C"导出,以获得最佳的跨语言兼容性(稍后我将从C#, C++,可能C和其他一些版本中使用此API)。显然,API不能包括整个类或其他c++特定的功能(如抛出异常),但我的问题是:

  1. 可以在导出的API中使用bool类型吗?毕竟,它是一个POD。
  2. 我可以使用不透明的指针类吗?如果是这样,我该如何在头文件中声明它们,以便头文件可以从C代码中使用?

Bool应该没问题,ABI和语言设计者对这些事情很小心(例如,来自c++的complex<double>和来自C的complex double被明确地设计为兼容)。类可以通过前向声明变成不透明的指针。

#ifdef __cplusplus
class MyClass;
#else
#include <stdbool.h>
typedef struct MyClass MyClass;
extern "C" {
#endif
bool IsActivated(MyClass *p, int x);
#ifndef __cplusplus
}
#endif

请注意,如果设置了各种编译器标志或属性,我已经看到了ABI兼容性问题——例如,如果启用了结构打包,在使用GCC 4.2的C和c++中bool的大小是不同的。

  1. 我可以在导出API中使用bool类型吗?毕竟,它是一个POD。 bool是c++特有的类型,如果你在头文件中使用它,它将无法在C中编译。此外,标准没有指定bool将如何实现,因此最好依赖于从int到bool的标准转换
  2. 我可以使用不透明的指针类吗? 我不知道你在这里不想达到什么目的。普遍接受的方法是将对象的生命周期封装在c++库中,并提供一组C函数来操作该对象。注意,即使你以某种方式允许通过指针访问你的类,你也会被命名混淆和调用约定
  3. 所困扰。

我最终进行了测试。以下是测试程序:

test_cpp.cpp:

#include "test.h"
class C {
    int a;
public:
    C() : a(42) {}
    int  getA() { return a; }
    void setA(int v) { a=v; }
};
int get7(bool b) { return b ? 7 : 3; }
C c;
C* getC() { return &c; }
int  getA(C* t) { return t->getA(); }
void setA(C* t, int v) { return t->setA(v); }

test_c.c:

#include <stdio.h>
#include "test.h"
int main()
{
    C* c = getC();
    printf("%dn", getA(c));
    setA(c, 10);
    printf("%dn", getA(c));
    printf("%dn%dn%dn%dn", get7(0), get7(1), get7(2), get7(-1));
    return 0;
}

test.h:

#ifdef __cplusplus
extern "C" {
#else
#define bool _Bool
#endif
struct C;
typedef struct C C;
int get7(bool b);
C* getC();
int  getA(C* t);
void setA(C* t, int v);
#ifdef __cplusplus
}
#endif

在windows上使用mingw64 gcc-4.9.0编译

gcc -c test_c.c
g++ test_cpp.cpp test_c.o

编译并正确运行。兴趣点:

  • g++完全没有问题,C被声明为struct,后来被定义为class
  • c++ boolc _Bool可以互换工作

我用MS编译器(VS2012)试过了,除了一个我无法解释的小细节外,它的工作原理是一样的:在头文件中,我不得不改变

int get7(bool b);

int get7(bool);

让它编译。如果有人能解释一下,我很乐意理解。