This proved to be quite the challenge, and is probably rather fragile, but it does seem to work, and might help with tracking down memory leaks.