on interfacing w/C++

Ellery Newcomer ellery-newcomer at utulsa.edu
Sun Apr 13 15:54:38 PDT 2014


(Putting this out there because it sounds like I'm going to get 
scooped in the near future)

So last week I was dinking around with the idea of a library to 
support calling C++ functions. So I wrote some ct code to emulate 
g++ 4.8.2's mangling scheme, and wrote a bit more code to wrap 
it, and calling conventions seemed to work out, and this is what 
I got:

for the C++:

class X {
     public:
         int i;

         X();
         int y();
         void z(int j);

         static int abu(int j);
};

do this:

mixin CppClass!("X",
     typeof(new class {
         int i;
         int y();
         void z(int j);

         static int abu(int j);
     }));
mixin(X.Externs); // waa, issue 12575


it generates something like

struct X {
     int i;
     int y() {
         return _ZN1X1yEv(&this);
     }
     void z(int j) {
         _ZN1X1zEi(&this, j);
     }
     static int abu(int j) {
         return _ZN1X3abuEi(j);
     }
}
extern(C) int _ZN1X1yEv(X*);
extern(C) void _ZN1X1zEi(X*,int);
extern(C) int _ZN1X3abuEi(int);


And it all seems to work. pointer params, reference params, 
variadic params, operators, templates all seem within ready reach.

virtual functions are going to be difficult - I guess you'd have 
to have a complete and accurate list of all fields in the class 
and all its superclasses. And all virtual functions. But g++ 
inserts a vtable symbol for classes with virtual functions - does 
anyone know what the heck that is?

Same for constructing a C++ object from within D - you need a 
valid sizeof.

other compilers won't work as above, the mangling scheme used by 
eg DMC doesn't produce valid D identifiers. Is there a pragma or 
anything to get around this?

And I totally spaced on exceptions until I looked on this forum a 
few minutes ago.

So my plan is to get all these bits implemented, then build a 
tool to validate the C++ and D sides match up, then build a tool 
to generate the D side from C++ headers. And then start expanding 
the list of supported C++ compilers.

Does this sound like a reasonable project? The points of concern 
I am worried about most are:

safety associated with supporting virtual functions
if a c++ mangler is stateful, that would shut me down pretty 
quick.
it requires the C++ compiler/version be specified at a library 
level
exceptions probably won't work


More information about the Digitalmars-d mailing list