Search code examples
pythoncocoapyobjc

Segfault in simple 2-line NSCountWindows call?


I'm trying to get window handles to currently available windows using PyObjC, with Mac OS X 10.7 and default Python 2.7. However, the following 2-liner causes Python to crash immediately. What gives?

bash-3.2$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from AppKit import *
>>> NSCountWindows(None)
Bus error: 10
bash-3.2$

The thread stack trace didn't help that much:

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_c.dylib               0x91167c19 _spin_lock$VARIANT$mp + 9
1   com.apple.CoreGraphics          0x990d0048 CGSGetOnScreenWindowCount + 87
2   com.apple.AppKit                0x9bdd13fd NSCountWindows + 61
... (Python internal calls)

Solution

  • Apple's frameworks don't particularly like when you use them without setting up an Application object. The corresponding C code also crashes:

    #import <AppKit/AppKit.h>
    #include <stdio.h>
    
    int main(void)
    {
       long windows;
    
       NSCountWindows(&windows);
       printf("%d\n", (int)windows);
       return 0;
    }
    

    The easiest workaround is to create an NSApplication object before calling APIs:

    import AppKit
    
    AppKit.NSApplication.sharedApplication()
    print AppKit.NSCountWindows(None)