Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

I am working on the API of a library I am writing. The library itself will be written in c++, but the API will be exported using extern "C" for best cross-language compatibility (I will be consuming this API later from C#, C++, maybe C and a few others).
Obviously, the API can't include whole classes or other c++ specific features (like throwing exceptions), but my questions are:

  1. Can I use the bool type in the exported API? After all, it is a POD.
  2. Can I use opaque pointers to classes? If so, how would I declare them in the header file so that the header file can be used from C code?
like image 565
Baruch Avatar asked Nov 11 '22 08:11

Baruch


1 Answers

Bool should be fine, the ABI and language designers are careful about these things (complex<double> from C++ and complex double from C are explicitly designed to be compatible, for example). Classes can be turned into opaque pointers with forward declarations.

#ifdef __cplusplus
class MyClass;
#else
#include <stdbool.h>
typedef struct MyClass MyClass;
extern "C" {
#endif

bool IsActivated(MyClass *p, int x);

#ifndef __cplusplus
}
#endif

Note that I have seen ABI compatibility issues if various compiler flags or attributes are set—for example, bool is a different size in C and C++ using GCC 4.2 if structure packing is enabled.

like image 157
Dietrich Epp Avatar answered Nov 15 '22 06:11

Dietrich Epp