Store or copy AXUIElementRef from callback

I'm trying to store an AXUIElementRef provided by an AXObserverCallback callback. When the callback scope ends, I believe the struct gets freed and I'm no longer able to use it elsewhere.

Is there a way to retain or copy this ref into my own data structure?

Here is the relevant code:

AXObserverCreate(..., &observer_callback, ...);
AXObserverAddNotification(..., ..., kAXWindowCreatedNotification, this);
void observer_callback(AXObserverRef observer, AXUIElementRef windowRef,
                       CFStringRef notificationName, void* inUserData) {
    applications* apps = (applications*)inUserData;

    if (CFEqual(notificationName, kAXWindowCreatedNotification)) {
        // memory error when trying to use windowRef outside of callback
    } else if (CFEqual(notificationName, kAXUIElementDestroyedNotification)) {

I know this is easily possible in Swift since this project does it.


  • Navigate one level up in the documentation to AXUIElement.h where it says:

    Each accessible user interface element in an application is represented by an AXUIElementRef, which is a CFTypeRef. AXUIElementRefs (like all CFTypeRefs) can be used with all the Core Foundation polymorphic functions, such as CFRetain, CFRelease, and CFEqual."