I have a C++ header file (named header.h
) which I want to include into my Swift project.
Since the C++ framework I want to include is not finished yet I just have the header file for now.
My C++ header file header.h
looks a little like this:
#include <vector>
struct someStruct{
float someAttr;
}
class someClass{
public:
enum SomeEnum{
Option1,
Option2
}
void someFunc(const double value) {}
}
Problem is, when I try to include the header.h
file in the project-Bridging-Header.h
it will never find vector which I include in header.h
I tried renaming header.h
to header.hpp
.
I tried setting the bridging headers Type to C++ Header in the right panel.
But none of them helped.
I hope some of you can help me figure out what I am doing wrong.
Unfortunately, it is not possible to use a C++ class in Swift directly, see https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216-CH2-ID0:
Actually, a convenient way of wrapping C++ for use in Swift is Objective-C++. Objective-C++ source files can contain both Objective-C and C++ code, mixed. Here is a quick partial example based on the code snippet in your question. Only
someClass
is partially wrapped here. In production code you would also need to consider memory management.The wrapper's header file,
mywrapper.h
, has no traces of C++:Here is the Objective-C++ implementation,
mywrapper.mm
. Please note the.mm
extension. You can create an Objective-C file with an.m
and then rename it.Now you can import
mywrapper.h
in the bridging header and then do something like this in Swift:Thus you can create an object in Swift, which is backed by an instance of your C++ class.
This is just a quick example to give you an idea. If your run into other problems, they would probably deserve separate questions.