Skip to content

re. Can you use a C++ class in C #1

Closed
@snej

Description

@snej

Good introduction, but there are ways to make this binding simpler and better. I just wrote about this on lobste.rs and I’ll copy it below.

FYI, if you want to see a large and complex example of a full C++ API wrapped in C, take a look at Couchbase Lite Core, my main work project. This C API is in turn used by language bindings in Objective-C, Swift, Java, Kotlin and C#.

——

I’ve done a lot of wrapping-C++-in-C in my career. This is a good basic intro, but there are several things that can be done better.

First, it’s much simpler to use extern “C” — you don’t need to go to the lengths of making a macro for it! You just put a curly-braced block after it, and the C-ness applies to everything in that block. The super-common idiom for this is:

#ifdef __cplusplus
externC” {
#endif
    // … any number of declarations here ...
#ifdef __cplusplus
}
#endif

Second, using void* to represent an object pointer loses type-safety. It’s quite easy to do better. Another common idiom:

#ifndef __cplusplus
typedef struct Rational Rational;
#endif
extern_c Rational *make_rational(int numer, int denom);
extern_c int get_numer(const Rational *r);
extern_c int get_denom(const Rational *r);
extern_c void del_rational(Rational **rp);

This tells the C compiler there’s a struct called Rational, but the compiler never sees (nor needs to see) its definition since you only ever declare pointers to it. It’s an opaque type.

Note that the accessors take a const pointer. This is a very good practice to follow. It makes const Rational* a read-only reference, so you can pass that type around and be assured that the called function(s) won’t modify (or free!) the object. (Unless they’re evil and cast away the const, but you wouldn’t do that, right?)

As a bonus, if the C++ class Rational is in the default namespace, these actually refer to the same type, so in your C++ implementations of make_rational etc. you don’t need to do any type-casting. However, that’s not usually the case, since a good C++ API puts its declarations in a unique namespace; so generally your implementations do have to cast between e.g. mymath::Rational* and ::Rational*. But it’s a small price to pay for type-safety.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions