Best way to go about wrapping C++ .hpp files to use from Swift

So, hi everyone! I am in a bit of a pickle and was gonna ask for help. So, I have a decent implementation of Vulkan and GLFW in Swift coming along on the Open Source NYON project. I want to use the C++ library GLM from Swift however the issue is all of it's header files are .hpp files. What is the best way to possibly wrap .hpp files in a .h C file or somehow get the library to work in swift using SwiftPM. I could switch to a C library alternative but C++ seems to be the main in terms of math libraries. Any ideas? Thank you all so much as always

You can't call C++ routines directly from Swift at this point in time (some experimental/development efforts from TensorFlow and others, not withstanding). You have to build a wrapper in Objective-C/Objective-C++, or C, to call C++ routines. If you are doing this on Linux or Windows, you'll probably end up using C, if you want to access the C++ library. If you have an alternate C library that you can use, it might be easier. I use Swift with C++, but, I program pretty much on MacOS, and use Objective-C++ as an intermediary.

1 Like

Since GLM is header only, you'll probably have to write C++ wrapper routines that can incorporate the headers libraries, and presents a C-interface that can put into a header file for use in the Swift bridging header.


Is there a reason you wouldn’t use a Swift maths library directly? For example, I use GitHub - troughton/SwiftMath: Math library for swift for all my graphics work, which is my own fork of a mixture of GitHub - SwiftGFX/SwiftMath: Cross-platform math library with SIMD support and GitHub - SwiftGL/Math: SwiftGL Math Library.

If you wrap a C library, you’re relying on link-time optimisations or inlining to make sure all of the operations are as fast as possible when used from Swift, whereas using a Swift library means the compiler gets the full view of any operations. There’s also usability – things like operator overloading tend to be fairly useful for maths, which a Swift native library will give you but would have to be reimplemented for a wrapped library.


I'm gonna look into your library it looks fantastic! Thank you so much!