segmentation fault while using ctypes

MRAB google at
Wed Apr 15 02:15:24 CEST 2009

Aaron Brady wrote:
> On Apr 14, 6:04 pm, sanket < at> wrote:
>> On Apr 14, 4:00 pm, MRAB <goo... at> wrote:
>>> sanket wrote:
>>>> Hello All,
>>>> I am dealing with this weird bug.
>>>> I have a function in C and I have written python bindings for it using
>>>> ctypes.
>>>> I can call this function for couple of times and then suddenly it
>>>> gives me seg fault.
>>>> But I can call same function from a C code for any number of times.
>>>> I cannot get what's going on.
>>>> here is my code.
>>>> /**********************************************/
>>>> /* C Function I am calling */
>>>> int get_hash(char *filename,int rate,int ch,unsigned char* hash,
>>>> unsigned int* hash_size,short* avg_f,short* avg_d){
> snip
>>>> Python code
>>>> ---------------------------------------------------------------------
>>>> from ctypes import *
>>>> lib = cdll.LoadLibrary("/usr/lib/")
>>>> def my_func(filename,rate,ch):
>>>>     hash = (c_ubyte * 424)()
>>>>     hash_size = c_uint()
>>>>     avg_f = c_short(0)
>>>>     avg_d = c_short(0)
>>>>     n = lib.get_hash(filename,rate,ch,hash,byref(hash_size),byref
>>>> (avg_f),byref(avg_d))
>>>>     hash = None
> snip
>> Thank you for your reply.
>> I will make check for fp and data pointers.
>> But my point is this function runs fine while calling it from a C
>> code.
>> it only breaks while calling from python. So I wonder if there can be
>> anything wrong with ctypes module.
>> Thanks,
>> sanket
> If you have console output available, you should printf the parameters
> as soon as you get into the function.  You can also return immediately
> for debugging purposes, to see if it's the call or the function body.
> You can also assign the 'argtypes' and 'returntype' members of a
> ctypes function call, which you didn't do, and may or may not help.
Instead of printf you could open a log file and use fprintf. I'd also
probably recommend setbuf(log_file, NULL) to disable buffering just
after opening the log file so that the logging is written immediately to
disk because otherwise you won't might not get all the logging if it

More information about the Python-list mailing list