don-prog don-prog - 1 year ago 106
Objective-C Question

Different C++ include statements throws errors in the Objective-C header

I'm trying to use OpenCV in Objective-C++ code which I will call from Swift. First I used this answer for connecting Objective-C and Swift. So after these manipulations I get three files:


#import "opencvtest.h"


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <opencv2/core/core.hpp>
//#include <dlib/image_loader/load_image.h>

@interface CustomObject : NSObject

- (cv::Mat)cvMatFromUIImage:(UIImage *)image;


#import "opencvtest.h"


/Users/user/Documents/XcodeProjects/Swift_HelloWorld/Swift_HelloWorld/Swift_HelloWorld-Bridging-Header.h:5:9: note: in file included from /Users/user/Documents/XcodeProjects/Swift_HelloWorld/Swift_HelloWorld/Swift_HelloWorld-Bridging-Header.h:5:
#import "opencvtest.h"
^ /Users/user/Documents/XcodeProjects/Swift_HelloWorld/Swift_HelloWorld/opencvtest.h:23:4: error: expected a type
- (cv::Mat)cvMatFromUIImage:(UIImage *)image; ^ <unknown>:0: error: failed to import bridging header '/Users/user/Documents/XcodeProjects/Swift_HelloWorld/Swift_HelloWorld/Swift_HelloWorld-Bridging-Header.h'

Also, if I add line
#include <dlib/image_loader/load_image.h>
in the opencvtest.h then I get:

/usr/local/include/DLIB/string/string.h:7:10: error: 'sstream' file not found
#include <sstream>
<unknown>:0: error: failed to import bridging header '/Users/user/Documents/XcodeProjects/Swift_HelloWorld/Swift_HelloWorld/Swift_HelloWorld-Bridging-Header.h'

I want to note that all these errors occurs only when I put these include statements in this header, when I used it in .mm file all works fine. But I need them in the header for declarations.

So, how can I fix it?

Answer Source

The interface of your Objective-C objects usable in Swift and thus visible in the bridging header cannot reference any C++ types. You need to write an Objective-C++ wrapper in such a way that C++ types are only mentioned in your .mm files and in headers used in the .mm files. You can hide the parts of the interface that use C++ by using extensions in Objective-C++ code. Please see the following question and questions referenced there for examples of how to do that:

objective C opencv wrapper for swift project does not see STL headers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download