tags:

views:

887

answers:

5

Hi,

I want to generate C wrappers from C++ libraries. There are tutorials on how to do it by hand:

But it is too much of a manual labor.

For example, for this:

struct RtAudio {
    virtual DeviceInfo const& f() {...}
    class DeviceInfo {
        virtual void g() { ... }
    };
    ...
};

I need to write:

struct RtAudioC {
    RtAudio x;
};
struct DeviceInfo {
    RtAudio::DeviceInfo x;
};
extern "C" {
    RtAudioC* newRtAudio() { 
        return new RtAudioC;
    }
    void deleteRtAudio(RtAudioC *p {
        delete p;
    }
    /* do something with RtAudio::f() */
    void g(DeviceInfo *p) {
        try {
            p->x.g();
        } catch (SomeError & err) {
        }
    }
}

Are there tools that can automate this process?

Thank you.

+1  A: 

There is gmmproc which creates C++ wrappers for gobject based C libraries, but that's the only code generator I've heard of between C and C++.

If you're good with writing a parser, it wouldn't be too difficult a task to create a basic wrapper generator. In the end you might have to add a few finishing touches manually, but still your work load would be reduced.

Sahasranaman MS
+1  A: 

You can try SWIG, C code generator was last year's GSoC project. AFAIK they haven't merged it to the trunk yet, so you'd have to checkout & build the branch from SVN.

Taavi
A: 

I don't know of an off-the-shelf tool to do this. If you want to automate the generation and are happy to write your own scripts, pygccxml (based on GCC-XML) is quite a nice way to parse C++ headers.

user9876
A: 

To do this right, you need a full C++ parser with name and type resolution. You also need tools that can visit the parsed C++ and the constructed symbol tables, and generate corresponding C code, best done from schematic patterns that capture the basic C skeletons. A tool that can be used to implement this is the DMS Software Reengineering Toolkit, which provides general parsing, symbol table construction, tree analysis/construction and prettyprinting, and its industrial strength C++ front end. See www.semanticdesigns.com/Products/FrontEnds/CppFrontEnd.html

Ira Baxter
+1  A: 

How much of your C++ code is already written vs. how much has yet to be written? If a reasonable proportion is to-be-written, I would create a simplified syntax, that generates both the C++ and C headers, like IDL does for COM interfaces. This simplified syntax will be much easier for you to parse than C++, or you can likely find something off the shelf that does this.

Drew Hoskins