2

I'm wanting to export my C++ classes as a library. I know this cannot be done easily since names are munged. I know you can export C functions from C++. I had heard that Swig may be what I'm looking for. I see that Swig can export C++ to C. I'm wondering if Swig also has the ability to then wrap those C functions in a header-only C++ file. I'm looking for something like this:

This base code:

class Point {
    public:
        Point(int x,int y);
        int getX();
        int getY();
}

Transforms into this C Code:

CPoint* CPoint_alloc(int x,int y);

int CPoint_getX(CPoint* p);
int CPoint_getY(CPoint* p);

Then the following C++ header would be generated to wrap the C code:

class Point {
    CPoint* p;
    public:
        Point(int x,int y){
            p = Point_alloc(x,y);
        }

        int getX(){
            return CPoint_getX(p);
        }

        int getY(){
            return CPoint_getY(p);
        }
}

Can Swig generate the C++ header? Or is there some other tool I can use?

Thanks

Kyle
  • 3,935
  • 2
  • 30
  • 44
  • There exists a summer school project, which enables SWIG to convert to plain C. See https://stackoverflow.com/questions/8303801/how-can-i-generate-c-wrappers-over-c-api-using-swig?answertab=active#tab-top – Jens Munk Mar 27 '18 at 20:33
  • @JensMunk Yeah, actually swig already converts C++ to plain C out of the box. You'd just pick any platform target and intermediate C code would be created for the bindings. I need a way to then take that C code an create an hpp file that re-wraps it back into a C++ library. – Kyle Mar 28 '18 at 16:41
  • That's not a good approach. The summer school project delivers more clean plain C code. If you pick a platform target, you will get a lot of boiler plate source that you would like to avoid. If the input is C++ you will get very nice plain C code with a type library. I don't see any point in going back to C++ – Jens Munk Mar 28 '18 at 17:08
  • @JensMunk I'd like to go back to C++ for simplicity when using my library. Basically being able to use the library as it was written but having it work across compilers. – Kyle Mar 28 '18 at 17:52
  • That makes sense. The original c++ library compiled using one compiler, the C wrapper and the C++ wrapper compiled using another compiler. You should check out the summer project - I use it myself. – Jens Munk Mar 28 '18 at 20:49

0 Answers0