Scripts/instrumentSends
=======================

* :download:`Download example <instrumentSends.py>`

...


instrumentSends.py
..................

.. sourcecode:: python

    """
    Warning: this script uses an undocumented, private API of the Objective-C
    runtime.
    
    It sometimes is useful to see which Objective-C methods are called in a
    program. Luckily the Objective-C runtime contains a private API for logging
    all method calls. This file shows how to call that API.
    """
    
    import Foundation
    import objc
    
    
    objc.loadBundleFunctions(
        Foundation.__bundle__,
        globals(),
        [("instrumentObjcMessageSends", objc._C_VOID + objc._C_NSBOOL)],
    )
    
    # To enable
    #  - the logfile will be created as ``/tmp/msgSends-<PID>`` (where ``<PID>``
    #    is the process-id of the process that calls the function.
    #  - the file contains a list of method names, somethink like this::
    #
    #     - NSClassicMapTable NSClassicMapTable objectForKey:
    #     - NSClassicMapTable NSClassicMapTable objectForKey:
    #     - NSClassicMapTable NSClassicMapTable objectForKey:
    #     + NSObject NSObject alloc
    #     + NSObject NSObject allocWithZone:
    #
    # - in PyObjC scripts you'll see a lot of calls that have nothing to do
    #   with you're program itself but are generated by the bridge code (such
    #   as all NSClassicMapTable calls in the example in the previous item).
    
    instrumentObjcMessageSends(True)  # noqa: F821
    
    # To disable
    instrumentObjcMessageSends(False)  # noqa: F821

