Skip to content

Instantly share code, notes, and snippets.

@uliwitness
Created February 23, 2017 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uliwitness/3a2b49d84bed992f997da973822a6354 to your computer and use it in GitHub Desktop.
Save uliwitness/3a2b49d84bed992f997da973822a6354 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#include <functional>
@class ObjCObject;
template<class p1type,class p2type>
class cpp_adapter2
{
public:
static void myImp( ObjCObject* self, SEL cmd, p1type a, p2type b );
std::function<void(p1type,p2type)> mFunction;
};
@interface ObjCObject : NSObject
{
cpp_adapter2<int,int> mAdapter;
}
-(cpp_adapter2<int,int>&) adapter;
@end
@implementation ObjCObject
-(cpp_adapter2<int,int>&) adapter
{
return mAdapter;
}
@end
template<class p1type,class p2type>
void cpp_adapter2<p1type,p2type>::myImp( ObjCObject* self, SEL cmd, p1type a, p2type b )
{
self.adapter.mFunction( a, b );
}
@interface ObjCObject (JustForTesting)
-(void) theMethod: (int)a with: (int)b;
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
ObjCObject * obj = [ObjCObject new];
obj.adapter.mFunction = [](int a, int b){ NSLog( @"called: %d %d", a, b ); };
class_addMethod( [ObjCObject class], @selector(theMethod:with:), (IMP)cpp_adapter2<int,int>::myImp,
"v@:ii" );
[(id)obj theMethod: 1 with: 2];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment