[swift-users] Using C++ libraries in Swift projects?
Jens Alfke
jens at mooseyard.com
Fri Jan 13 10:43:46 CST 2017
> On Jan 13, 2017, at 8:18 AM, Ethin Probst via swift-users <swift-users at swift.org> wrote:
>
> I was wondering how I could go about using the Boost library project
> (among others) in swift?
No, it’s generally not feasible to use C++ libraries from any other language. The main reasons are that (a) name-mangling of C++ functions means that there’s no reliable way to tell the other language the name of the function you want to call, and (b) C++ has so many language features that are tightly entwined with the way you call functions — constructors, copying, assignment, references, implicit conversions, operator overloading, etc.
In the simple example you gave there are several warning signs:
* BOOST_LOG_TRIVIAL etc. appear to be macros since they’re in all caps. Who knows what functions they actually call?
* The “<<“ operator expands [unmangles] to some complex function name which is very compiler-dependent.
* It’s very probable that the “<<“ operator is defined as an inline function, so it may not even appear in the binary of the compiled Boost library at all.
* The C string constants on the right hand side are probably being implicitly converted to C++ std::strings before the call. Or maybe not. And the conversion likely happens on the caller’s side, i.e. the compiler has to know to create a std::string before calling and then destruct it afterwards.
The only practical way to call a C++ API from another language is to write glue code, a set of functions that call the library, but which have a plain C API and use only C types. Pretty much any language has a way to call C functions, so you can now call the C API which will call the C++ code.
—Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170113/57392f63/attachment.html>
More information about the swift-users
mailing list