[Python-ideas] {Python-ideas] C-API exposure

geremy condra debatem1 at gmail.com
Tue Mar 29 22:53:44 CEST 2011


On Tue, Mar 29, 2011 at 12:32 PM, Sturla Molden <sturla at molden.no> wrote:
> Den 29.03.2011 21:15, skrev Eric Snow:
>>
>> Well people already do this using ctypes...
>>
> Haven't used them myself yet.  So you can use them to expose all of the
> C-API?  Cool!
>
>
> Yes, ctypes.pythonapi exposes the Python C API to Python.
>
> You can use it for evil code like this hack to prevent thread switch
> (doesn't work with Python 3, as the implementation has changed). Just make
> sure you don't call extension code that releases the GIL, or all bets are
> off ;-)
>
> Sturla
>
>
>
> from contextlib import contextmanager
> import ctypes
> _Py_Ticker = ctypes.c_int.in_dll(ctypes.pythonapi,"_Py_Ticker")
>
> @contextmanager
> def atomic():
>     tmp = _Py_Ticker.value
>     _Py_Ticker.value = 0x7fffffff
>     yield
>     _Py_Ticker.value = tmp - 1
>
> Now we can do
>
> with atomic():
>     # whatever
>     pass

Huh. That's terrifying. Thanks for the example.

Geremy Condra



More information about the Python-ideas mailing list