1

I am trying to tap into the HID events of OSX. I found a snippet for testing it. However my code always seem to fail with EXC_BAD_ACCESS at the CFMachPortCreateRunLoopSource line. It seems that downEventTap is null. Reading the documentation tells me that this needs to be run on the main thread, I am pretty sure I am on the main thread, and wrapping things up in dispatch_async(dispatch_get_main_queue(), ^{ still gives me null. I am calling listen from application didFinishLaunching and added

@interface AppDelegate (){
  CFRunLoopSourceRef downSourceRef;
}

This is how I think creating an Event tap is to be done:

CGEventRef onKeyDown(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
  NSLog(@"DOWN (%lli)", CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode));
  // When it matches, I return CGEventCreate(NULL) to stop the event
  return event;
}
-(void)listen{

  CFMachPortRef downEventTap = CGEventTapCreate(kCGHIDEventTap,kCGHeadInsertEventTap,kCGEventTapOptionDefault,CGEventMaskBit(kCGEventKeyDown),&onKeyDown,(__bridge void *)(self));
  downSourceRef = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, downEventTap, 0); //<-- Crash exc_bad_access: downEventTap = 0x0,downSourceRef= 0x0
  CFRelease(downEventTap);
  CFRunLoopAddSource(CFRunLoopGetCurrent(), downSourceRef, kCFRunLoopDefaultMode);
  CFRelease(downSourceRef);
}
David Karlsson
  • 9,396
  • 9
  • 58
  • 103
  • Hey there David, I was just wondering if main thread was required for CGEventTapCreate, I was looking for a way to monitor mouse events from off main thread. – Noitidart Oct 19 '15 at 01:30
  • 1
    I don't know actually, just tried it to be on the safe side if I recall correctly... Try another thread and see what happens... – David Karlsson Oct 19 '15 at 10:33
  • Thanks! I tested and it seems to be ok im having an issue with the run loop: http://stackoverflow.com/q/33209518/1828637 – Noitidart Oct 19 '15 at 10:53
  • @DavidKarlsson so, what was the workaround? – dollar2048 Nov 19 '16 at 00:22

1 Answers1

2

You most likely do not have the permissions required to tap the event which causes CGEventTapCreate to return NULL, which causes CFMachPortCreateRunLoopSource to segfault when trying to dereference said NULL.

Fjölnir
  • 490
  • 2
  • 12