Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Last active June 22, 2019 00:46
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 yohhoy/42276cf68b931e7fdda25d5fd038c803 to your computer and use it in GitHub Desktop.
Save yohhoy/42276cf68b931e7fdda25d5fd038c803 to your computer and use it in GitHub Desktop.
// callee.m iOS Native(Objective-C) class
@interface NativeType
- (void)method:(int)arg;
@end

@implementation NativeType
// ...
@end
// bridge.m: C#/ObjC bridge code
struct NativeTypeTag;
typedef const struct CF_BRIDGED_TYPE(NativeType) NativeTypeTag* NativeTypeRef;

NativeTypeRef NativeType_init()
{
  NativeType *self = [[NativeType alloc] init];
  return (NativeTypeRef)CFBridgingRetain(self);
}

int NativeType_method(NativeTypeRef ref, int arg)
{
  __weak NativeType *self = (__bridge NativeType *)ref;
  return [self method:arg];
}

void NativeType_free(NativeTypeRef ref)
{
  __weak NativeType *self = (__bridge NativeType *)ref;
  CFRelease((CFTypeRef)self);
}
// caller.cs: Unity script(C#) hanlder class
class NativeHandler {
  private IntPtr nativeObj;

  public NativeHandler() {
    nativeObj = NativeType_init();
  }

  ~NativeHandler() {
    NativeType_free(nativeObj);
  }

  public int method(int arg) {
    return NativeType_method(nativeObj, arg);
  }

  [DllImport("__Internal")]
  private static extern IntPtr NativeType_init();
  [DllImport("__Internal")]
  private static extern int NativeType_method(IntPtr ref, int arg);
  [DllImport("__Internal")]
  private static extern void NativeType_free(IntPtr ref);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment