Adding C++ Object to Objective-C Class
-
20-09-2019 - |
Question
I'm trying to mix C++ and Objective-C, I've made it most of the way but would like to have a single interface class between the Objective-C and C++ code. Therefore I would like to have a persistent C++ object in the ViewController interface.
This fails by forbidding the declaration of 'myCppFile' with no type:
#import <UIKit/UIKit.h>
#import "GLView.h"
#import "myCppFile.h"
@interface GLViewController : UIViewController <GLViewDelegate>
{
myCppFile cppobject;
}
@end
However this works just fine in the .mm implementation file (It doesn't work because I want cppobject to persist between calls)
#import "myCppFile.h"
@implementation GLViewController
- (void)drawView:(UIView *)theView
{
myCppFile cppobject;
cppobject.draw();
}
Solution
You should use opaque pointers and only include C++ headers in the file that implements your Objective-C class. That way you don't force other files that include the header to use Objective-C++:
// header:
#import <UIKit/UIKit.h>
#import "GLView.h"
struct Opaque;
@interface GLViewController : UIViewController <GLViewDelegate>
{
struct Opaque* opaque;
}
// ...
@end
// source file:
#import "myCppFile.h"
struct Opaque {
myCppFile cppobject;
};
@implementation GLViewController
// ... create opaque member on initialization
- (void)foo
{
opaque->cppobject.doSomething();
}
@end
OTHER TIPS
Make sure that all files that include GLViewController.h
are Objective-C++ sources (*.mm).
When you include C++ code in the header of your view controller, all sources that import this header must be able to understand it, so they must be in Objective-C++
You need to declare the C++ objects in an interface block in your .mm file.
In .mm:
#include "SomeCPPclass.h"
@interface SomeDetailViewController () {
SomeCPPclass* _ipcamera;
}
@property (strong, nonatomic) UIPopoverController *masterPopoverController;
- (void)blabla;
@end
I think you need to set the following flag to true
in your project settings:
GCC_OBJC_CALL_CXX_CDTORS = YES
This should allow you to instantiate C++ objects in your Objective-C classes.