Reputation: 12444
I'm going to write a lot of C++ functions for my Objective-C code (due to third-party functions). And I was thinking it may be a good idea to abstract out the C++ code by having a intermediate Objective-C++ file wrapper between the Objective-C code and the C++ code. The layout as I have it currently is the ViewController.m file creates an instance of my wrapper Objective-C++ class. This class calls it's instance methods which in turn call the C++ code. A simple version of this is given below. Is this a bad way to do this? Is there a more appropriate way to approach this? Any other criticisms with the code as is? Thank you much!
ViewController.m
#import "ViewController.h"
#import "CppWrapper.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CppWrapper *wrap = [[CppWrapper alloc] init];
double n = 5;
n = [wrap cppTimesTwo:n];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
CppWrapper.mm
#import "CppWrapper.h"
#import "Cpp.h"
@implementation CppWrapper
- (double)cppTimesTwo:(double) number
{
return timesTwo(number);
}
@end
Cpp.cpp
#include "Cpp.h"
double timesTwo(double number)
{
return 2 * number;
}
Upvotes: 3
Views: 1374
Reputation: 811
We did the same thing in a project to reuse some C source code and it worked very well. I think it is a good way to do this.
Upvotes: 2