3

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;
}
3
  • just make sure your .h file does not contain any C++ code Commented Oct 31, 2013 at 0:28
  • @BryanChen: Which .h file? Commented Oct 31, 2013 at 0:56
  • all .h file used by .m file. in this case, CppWrapper.h Commented Oct 31, 2013 at 1:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.