Oh, goodness, Objective-C++ is a bit of a dark art (-: The language itself is pretty obvious: You subtract C from Objective-C to get the ‘Objective-’ bits, and then you add those to C++. However, there’s a bunch of subtlety here and it’s not something that I’ve used a lot.
OK, so, let’s see if I can create an example, but only if you forgive my terribly C++ (-:
Start with a C++ class like this:
---------------------------------------------------------------------------
// CPPTest.hpp
#ifndef CPPTest_hpp
#define CPPTest_hpp
class CPPTest {
public:
CPPTest();
~CPPTest();
void test();
};
#endif /* CPPTest_hpp */
---------------------------------------------------------------------------
// CPPTest.cpp
#include "CPPTest.hpp"
#include "stdio.h"
CPPTest::CPPTest() {
printf("construct\n");
}
CPPTest::~CPPTest() {
printf("destruct\n");
}
void CPPTest::test() {
printf("Hello Cruel World!\n");
}
---------------------------------------------------------------------------
Note You can tell I’m scared of C++ because I’m using the C stdio
library here (-:
Wrap that in an Objective-C++ class like this:
---------------------------------------------------------------------------
// OCPPTest.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface OCPPTest : NSObject
- (instancetype)init;
- (void)test;
@end
NS_ASSUME_NONNULL_END
---------------------------------------------------------------------------
// OCPPTest.mm
#import "OCPPTest.h"
#include <stdio.h>
#include "CPPTest.hpp"
@implementation OCPPTest {
CPPTest * _cppTest;
}
- (instancetype)init {
printf("init\n");
self = [super init];
if (self != nil) {
self->_cppTest = new CPPTest();
}
return self;
}
- (void)dealloc {
printf("dealloc\n");
delete self->_cppTest;
}
- (void)test {
self->_cppTest->test();
}
@end
---------------------------------------------------------------------------
Then import that class into your Swift bridging header:
---------------------------------------------------------------------------
// OCPPMadness-Bridging-Header.h
#import "OCPPTest.h"
---------------------------------------------------------------------------
Finally, call it from Swift:
---------------------------------------------------------------------------
// main.swift
func main() {
let o = OCPPTest()
o.test()
}
main()
---------------------------------------------------------------------------
I tested this with a command-line tool project in Xcode 12.5. When I ran the tool it prints:
init
construct
Hello Cruel World!
dealloc
destruct
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"