[C++-sig] ctypes newbie question

Gary Robinson garyrob at mac.com
Thu Jun 5 19:34:00 CEST 2008


On OS X 10.5.3, with Python 2.5.2, I have the following C function, called test2.c:

==============
double testreturn(void)
{
  return  105.0;
}
==============

I also have the following Python script:

==============
from ctypes import *

testreturnproto = CFUNCTYPE(c_double)
testreturn = testreturnproto(CDLL('test2.dylib').testreturn)
print 'prototype version returned: ', testreturn()

testdll = CDLL('test2.dylib')
testdll.testreturn.restype = c_double
print 'non-prototype version returned:', testdll.testreturn()
=============

Based on reading the ctypes docs, I would expect the output of the script to be:

prototype version returned:  105.0
non-prototype version returned: 105.0

However, what I actually get is:

prototype version returned:  872440.0
non-prototype version returned: 105.0

If I modify the python script by commenting out the assignment to restype, the new script and results are:

================
from ctypes import *

testreturnproto = CFUNCTYPE(c_double)
testreturn = testreturnproto(CDLL('test2.dylib').testreturn)
print 'prototype version returned: ', testreturn()

testdll = CDLL('test2.dylib')
#testdll.testreturn.restype = c_double
print 'non-prototype version returned:', testdll.testreturn()
================

prototype version returned:  872440.0
non-prototype version returned: 872440

I assume that this means that the double 105.0 is being interpreted as if it were an int, since the default result type as an int.

What I don't understand is why the line

  testreturnproto = CFUNCTYPE(c_double)

is apparently not causing the return type to be properly interpreted as a double. We know that it's ultimately causing a Python float to be created, since the printed output ends with .0. So it has received the information that the number is supposed to be a float. But it's still interpreting it as an int before instantiating it as a float.

The ctypes reference describes CFUNCTYPE as follows:

> CFUNCTYPE(restype, *argtypes)
> The returned function prototype creates functions that use the 
> standard C calling convention. 

I am passing c_double as restype. So why is it apparently interpreting the result as an int?

I guess I don't understand the purpose of instantiating a prototype with CFUNCTYPE if it doesn't take care of interpreting the result as the type you give it.

Any insight/help would be appreciated.

Thanks,
Gary

-- 

Gary Robinson
CTO
Emergent Music, LLC
personal email: garyrob at mac.com
work email: grobinson at emergentmusic.com
Company: http://www.emergentmusic.com
Blog:    http://www.garyrobinson.net



More information about the Cplusplus-sig mailing list