How to interop between Objective-C and C++?

Using Objective-C++

You can transform your Objective-C file (.m) to Objective-C++ (.mm). This by default enables you to call any C++ code in your Objective-C++ file.



#include “SomePrivateCppClass.h”
@implementation MyObjective_c_file
- (instancetype) init
{
// Add your logic here
SomePrivateCppClass::someMethod();
}
@end

Interopping with a C interface to call an Objective-C function from C++

When file separation is required due to external dependencies. You can interop by using a C interface.


void callFromCpp(const char *dataPayload);
@implementation MyObjective_c_file

— (void)myMethod: (NSString *) dataPayload {
// Your logic here
}
@endvoid callFromCpp(const char *dataPayload) {
NSString *convertedString = [[NSString alloc] initWithCString: dataPayload encoding:NSUTF8StringEncoding];

MyObjective_c_file myInstance = [[MyObjective_c_file alloc] init];
[MyObjective_c_file myMethod: convertedString];
}


YourCppClass::WhatEverMethod() {
callFromCpp(stringData.c_str());
}

Passing pointers with a C interface to call a C++ method.

When using a C interface, you can also pass a pointer of your C++ class in order to call it from your Objective-C++ code (This is ideal when you can’t include your C++ file due to dependencies).


void initFromCpp(long castBridgePointer);

#include “YourCppClass.h”
@implementation MyObjective_c_file
static YourCppClass *pointerToBridge;

- (void)storeCastBridgePointer: (long) ptr {
pointerToBridge = (YourCppClass *) ptr;
}
@endvoid initFromCpp(long castBridgePointer)
{
MyObjective_c_file myInstance = [[MyObjective_c_file alloc] init];
[myInstance storeCastBridgePointer: castBridgePointer];
}


YourCppClass::YourCppClass() {
// whatever logic…
initFromCpp((long) this);
}

Conclusion

Interop between C++ and Objective-C is not too complicated. The purpose of this post is to bring both solutions, the plain Objective-C approach and C interface approach, into a single post where anyone can reference in the future

--

--

Software Engineer - Head Of Vetting At G2i

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrei Calazans

Andrei Calazans

Software Engineer - Head Of Vetting At G2i