Skip to content

Instantly share code, notes, and snippets.

@OsamuTakahashi
Created December 13, 2009 13:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OsamuTakahashi/255412 to your computer and use it in GitHub Desktop.
Save OsamuTakahashi/255412 to your computer and use it in GitHub Desktop.
bridge between C++ and Objective-C
#include <objc/objc.h>
#define BRIDGE_TO( A ) \
static void *operator new(size_t ,void *in_memory) { return in_memory; } \
static void *operator new(size_t in_size) { return alloc(in_size,#A); } \
static void operator delete(void *in_memory) { dealloc(in_memory); }
class _BridgeBase
{
public:
BRIDGE_TO( BridgeBase )
_BridgeBase() {}
virtual ~_BridgeBase() {}
static void *alloc(size_t in_size,const char *in_objcClassName);
static void dealloc(void *);
};
template<typename T>
T objc2cpp_cast(id obj) { return (T)((unsigned char *)obj + sizeof(void *)); }
template<typename T>
id cpp2objc_cast(T obj) { return (id)((unsigned char *)obj - sizeof(void *)); }
#include <CoreFoundation/CoreFoundation.h>
#include <objc/objc-runtime.h>
#include "_BridgeBase.h"
void *
_BridgeBase::alloc(size_t in_size,const char *in_objcClassName)
{
id klass = objc_getClass(in_objcClassName);
unsigned char *p = (unsigned char *)NSAllocateObject(klass, in_size, NULL);
return p + sizeof(void *);
}
void
_BridgeBase::dealloc(void *in_space)
{
objc_class *obj = (objc_class *)((unsigned char *)in_space - sizeof(void *));
NSDeallocateObject(obj);
}
#import <Foundation/Foundation.h>
@interface BridgeBase : NSObject {
}
@end
#import "BridgeBase.h"
#import "_BridgeBase.h"
@implementation BridgeBase
+ (id)alloc
{
id obj = NSAllocateObject(self, sizeof(_BridgeBase), NULL);
new(objc2cpp_cast<_BridgeBase *>(obj)) _BridgeBase();
return obj;
}
+ (id)allocWithZone:(NSZone *)zone
{
id obj = NSAllocateObject(self, sizeof(_BridgeBase), zone);
new(objc2cpp_cast<_BridgeBase *>(obj)) _BridgeBase();
return obj;
}
- (void)dealloc
{
delete objc2cpp_cast<_BridgeBase *>(self);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment