classification
Title: ctypes.xFUNCTYPE are decorators.
Type: enhancement Stage:
Components: Documentation Versions: Python 3.0
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: LambertDW, georg.brandl, kevinwatters, theller
Priority: normal Keywords:

Created on 2008-11-05 05:51 by LambertDW, last changed 2010-10-29 10:07 by admin.

Messages (3)
msg75515 - (view) Author: David W. Lambert (LambertDW) Date: 2008-11-05 05:51
http://docs.python.org/dev/3.0/library/ctypes.html#callback-functions

ctypes.xFUNCTYPE are another opportunity to advertise decorators.  
Please consider inserting yet another qsort example written as a 
decorator, perhaps as follows.  Or---it could be that I'm slow and the 
average pythonista will figure this out on first read.


@CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
def py_cmp_func(*args):
    (a,b,) = (t[0] for t in args)
    print("py_cmp_func", a, b)
    return a-b

qsort(ia,len(ia),sizeof(c_int),py_cmp_func)
msg75535 - (view) Author: Kevin Watters (kevinwatters) Date: 2008-11-05 23:12
As far as I know, the above code will fail randomly in release mode if 
you have multiple threads running Python, because when ctypes calls out 
to CFUNCTYPE functions, it releases the GIL.

For decorating a python function to give to qsort, maybe you can use 
PYFUNCTYPE?
msg75577 - (view) Author: Thomas Heller (theller) * (Python committer) Date: 2008-11-06 18:48
[David Lambert]
> > @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
> > def py_cmp_func(*args):
> >     (a,b,) = (t[0] for t in args)
> >     print("py_cmp_func", a, b)
> >     return a-b
> > 
> > qsort(ia,len(ia),sizeof(c_int),py_cmp_func)

[Kevin Watters]
> > As far as I know, the above code will fail randomly in release mode if 
> > you have multiple threads running Python, because when ctypes calls out 
> > to CFUNCTYPE functions, it releases the GIL.
> > 
> > For decorating a python function to give to qsort, maybe you can use 
> > PYFUNCTYPE?

Kevin is wrong - the code is perfect!  Sure does calling a CFUNCTYPE instance
release the GIL, but ctypes aquires the GIL again before executing the python
code in the wrapped py_cmp_func above.

I guess that using PYFUNCTYPE instead would possibly crash because the call to
'qsort' releases the GIL, and the PYFUNCTYPE instance assumes the GIL but does not
acquire it.

But I have no time to work on the docs, sorry.
History
Date User Action Args
2010-10-29 10:07:21adminsetassignee: georg.brandl -> docs@python
2008-11-06 18:48:31thellersetnosy: + theller
messages: + msg75577
2008-11-05 23:12:11kevinwatterssetnosy: + kevinwatters
messages: + msg75535
2008-11-05 05:51:03LambertDWcreate