2

I'm trying to set up an event tap in swift using CGEventTapCreate(...). This takes a CGEventTapCallback function pointer as one of its arguments.

As far as I'm aware, there's no way to pass a swift function as a c function pointer in the current beta.


What I did instead was write the callback in Objective C, as usual:

// callback.h

CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event,
        void *refcon);

// callback.m

CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event,
        void *refcon)
{
    return NULL;
}

and then add the import to my bridging header:

// project-Bridging-Header.h

#import "callback.h"

This correctly exposes the function to swift. However, it does so by converting the type of the function to a swift func.

As a result, I still can't provide it as an argument to CGEventTapCreate(...)

Is there an inbuilt function which will transform a bridged function to a function pointer?

sapi
  • 9,944
  • 8
  • 41
  • 71
  • Provide in CGEventTapCreate swift's block, where you call yours callback. – Cy-4AH Aug 19 '14 at 09:29
  • @Cy-4AH - I don't believe `CGEventTapCreate` exposes a block param, but I'm happy to be proven wrong in an answer! – sapi Aug 19 '14 at 09:30
  • Things got better in Swift 2, see https://stackoverflow.com/questions/31891002/how-do-you-use-cgeventtapcreate-in-swift – Martin R Nov 14 '18 at 10:52

1 Answers1

1

I'm adding a workaround here, but I don't like it.

Basically, you just expose a function pointer directly:

// callback.h

CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event,
        void *refcon);
extern CGEventTapCallBack callback_ptr;

// callback.m

#import callback.h

CGEventTapCallBack callback_ptr = callback;

CGEventRef callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event,
        void *refcon)
{
    return NULL;
}
sapi
  • 9,944
  • 8
  • 41
  • 71