Mix Objective-C and C++ and OpenCV

2020-06-28 10:56发布

问题:

I'm coding an iPhone app and I'm using OpenCV for some image processing. I have only used it in plain C so far but now I need to use C++ to create some basic OCR.

I first created a .h/.cpp file and it seems to compile fine. But I need to mix this with some Objective-C to open images and so on. I then renamed the file to .mm instead for .cpp but it won't compile!

I get this error: "Statement-expressions are allowed only inside functions" in OpenCV core.hpp line 432

Line 432 is this line:

typedef Matx<_Tp, MIN(m, n), 1> diag_type;

Any ideas why this might happen?

回答1:

I had the same issue. I imported the Open-CV header before the UIKit headers. Make sure you do this in the pch file. The issue is with some macro defined in both UIKit and OpenCV.

Source: http://computer-vision-talks.com/2011/01/using-opencv-in-objective-c-code/

Maunil



回答2:

I actually relied on the private framework (and sample project) provided by this guy: http://aptogo.co.uk/2011/09/opencv-framework-for-ios/

I managed to use the same approach he did in the sample for use in my Objective-C mac app. Namely, the use of the import directive in the .PCH file as well as using .mm for Objective-C files that relied on any OpenCV C++ code/classes.



回答3:

Another (unrelated?) thing worth mentioning, at least in xcode 4.5, is that you have to change your C++ standard library to 'libstdc++' in your target settings to get openCV to compile.



回答4:

the OpenCV headers must be included before UIKit.h and Foundation.h because OpenCV defines a MIN macro that conflicts with the MIN function defined by the Apple frameworks. If you include the OpenCV headers after UIKit.h and Foundation.h you will receive compilation errors such as ‘LLVM GCC 4.2 Error: Statement-expressions are allowed only inside functions’. Including the OpenCV headers first and surrounding the #import with the __cplusplus conditional test avoids this problem and means that you can still use plain Objective-C for ‘.m‘ files in your project that don’t call the OpenCV APIs.

http://aptogo.co.uk/2011/09/opencv-framework-for-ios/