Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Last active November 26, 2018 14:48
Show Gist options
  • Save y-fedorov/eec304304b972f82bcccba7e52a34526 to your computer and use it in GitHub Desktop.
Save y-fedorov/eec304304b972f82bcccba7e52a34526 to your computer and use it in GitHub Desktop.
C++ to Objective-C accessor
#import "MyObject.h"
//--- pass by reference ---
MyObject *obj = [[MyObject alloc] init];
...
auto *cppObject = new MyObjectCpp(obj);
cppObject->SayHello("Hello!");
//---
...
//-- Create an instance of MyObject from cpp code ...
auto *cppObject = new MyObjectCpp();
cppObject->SayHello("Hello!");
//--
based on: "A shortcut for wrapping Objective-C objects in C++"
http://philjordan.eu/article/mixing-objective-c-c++-and-objective-c++
don't forget to turn off ARC:
You can disable ARC for individual files in XCode under the 'Build Phases' tab in the build target's properties.
Fold out the 'Compile Sources' section and add `-fno-objc-arc` to the compiler flags for the file(s) in question.
for MyObject.mm (`-fno-objc-arc`)
|- example.mm (Usage example)
|
|- MyObject.h (Objective-C header)
|- MyObject.mm (Objective-C + CPP part implementation)
|- MyObjectCpp.h (C++ header)
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyObject : NSObject
-(void)sayHello:(NSString *)string;
@end
NS_ASSUME_NONNULL_END
#import "MyObject.h"
#include "MyObjectCpp.h"
#include <string>
namespace abc {
MyObjectCpp::MyObjectCpp() : wrapped([[MyObject alloc] init]){
}
MyObjectCpp::MyObjectCpp(MyObject *obj):wrapped(obj) {
}
MyObjectCpp::~MyObjectCpp() {
[wrapped release];
}
void MyObjectCpp::SayHello(const std::string &text){
[wrapped sayHello:[NSString stringWithUTF8String:text.c_str()]];
}
}
@implementation MyObject
-(void)sayHello:(NSString *)string {
NSLog([NSString stringWithFormat:@"Say: %@", string]);
}
@end
#ifndef MyObjectCpp_h
#define MyObjectCpp_h
#include <string>
#import <objc/runtime.h>
#ifdef __OBJC__
#import "MyObject.h"
@class MyObject;
#else
typedef struct objc_object MyObject;
#endif
namespace abc {
class MyObjectCpp {
MyObject *wrapped;
public:
MyObjectCpp();
MyObjectCpp(MyObject *obj);
~MyObjectCpp();
void SayHello(const std::string &text);
};
}
#endif /* MyObjectCpp_h */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment