[C++-sig] [Py++] ctypes generator produces wrong Python code for function pointers in structs

Nikolaus Rath Nikolaus at rath.org
Fri Dec 25 23:43:55 CET 2009


Hello,

Py++ translates the struct

typedef int cb_fun_t(char *);
struct info {
   cb_fun_t* cb_fun;
   int flag;
};

into the Python Structure

class info(ctypes.Structure):
    """class info"""
info._fields_ = [ #class info
    ("cb_fun", ctypes.POINTER( ctypes.CFUNCTYPE( ctypes.c_int, ctypes.c_char_p ) )),
    ("flag", ctypes.c_int),
]

This is wrong and produces segfaults. The correct version is

class info(ctypes.Structure):
    """class info"""
info._fields_ = [ #class info
    ("cb_fun", ctypes.CFUNCTYPE( ctypes.c_int, ctypes.c_char_p ) ),
    ("flag", ctypes.c_int),
]


I have attached a small example that demonstrates the problem. lib.c is
a small C library, build_api.py creates the broken api.py with Py++.
api_correct.py is the manually corrected API with the correct structure.
call.py demonstrates that the first API segfaults and the second API
works:

$ python call.py 
Calling do_callback with flag=7
do_callback called with flag=7
cb_fun received 'Hello World'
cb_fun returns 42
cb_fun returned 42
do_callback returned 42
Calling do_callback with flag=7
do_callback called with flag=7
Segmentation fault


Please let me know if you can reproduce the problem. It took me quite
some time to figure this out.


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C
-------------- next part --------------
A non-text attachment was scrubbed...
Name: lib.c
Type: text/x-csrc
Size: 334 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20091225/1ea612ed/attachment.c>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: build_api.py
Type: text/x-python
Size: 499 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20091225/1ea612ed/attachment.py>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: api.py
Type: text/x-python
Size: 792 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20091225/1ea612ed/attachment-0001.py>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: api_correct.py
Type: text/x-python
Size: 775 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20091225/1ea612ed/attachment-0002.py>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: call.py
Type: text/x-python
Size: 650 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20091225/1ea612ed/attachment-0003.py>


More information about the Cplusplus-sig mailing list