Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - Creating a wrapper file for C++ functions?

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;
}
like image 553
golmschenk Avatar asked Dec 19 '25 16:12

golmschenk


1 Answers

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.

like image 170
Juliano Avatar answered Dec 22 '25 05:12

Juliano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!