How to create a cocoa framework from C++ and use it in Swift

I have a third party driver software with a lot of static libraries and a whole lot of headers. My goal is to wrap those libraries and headers into a cocoa framework, use an umbrella for all the headers that I need, and load this framework as a module into my Swift app. What I want to avoid is to copy all the headers into the public header section of the build settings.

When I import the C++ headers in the framework header I get a lot of error messages "Inlcude of non-modular headers inside framework module".

In the internet they say we can use the targets build settings to allow non-modular headers. But this doesn't worked either.


Some background why I want to do this. Sometimes we must switch back to older versions of the driver software. So my goal is to use git branches for each version and use them to build cocoa frameworks that I can use in my Swift app.


Has someone managed to build frameworks containing C++ libraries and their headers to use them within Swift projects already? I checked the internet and it seems to be not so easy as I thought.

Replies

It isn't that difficult, but it is pretty tedious.


You can't make any C++ visible to Objective-C/Swift. You have to structure all of your classes like this:


Objective-C header (MyClass.h): All public Objective-C methods or properties. Exported as "public" to the framework.


Private Objective-C header (MyClassPrivate.h): Includes the Objective-C header. All private methods or properties that need C++ defined as a category for the original class. Access set as "project" in the framework.


Objective-C++ implementation (MyClass.mm): Includes both the Objective-C header and the private Objective-C header.


If necessary, you can include Objective-C macros and/or a Swift header to adjust how the methods are imported into Swift.


The tedious part is that have to define and maintain your own Objective-C wrapper classes. Any updates to the underlying C++ will require manual updates to your wrappers. One trick I have found is if the C++ comes with good doxygen, you may be able to automate the generation of the wrappers. I'm using the C++ GDAL framework which has excellent documentation. After building GDAL documentation, I can manually run doxygen again and save intermediate XML files. Then, with a developer license for MarkLogic and a crazy XQuery script, I can generate the above file structures, complete with implementation code, for each C++ class.


I have done this manually and got it work work fine in Swift. The automated generation is still experimental.