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

Sturla Molden sturla at molden.no
Tue Mar 29 21:32:16 CEST 2011

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 ;-)


from contextlib import contextmanager
import ctypes
_Py_Ticker = ctypes.c_int.in_dll(ctypes.pythonapi,"_Py_Ticker")

def atomic():
     tmp = _Py_Ticker.value
     _Py_Ticker.value = 0x7fffffff
     _Py_Ticker.value = tmp - 1

Now we can do

with atomic():
     # whatever

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110329/4b506ad0/attachment.html>

More information about the Python-ideas mailing list