Reputation: 1413
I've faced with a problem when I tried to load float into python program using ctypes
C code:
float test_ret_float(){
return 1.0;
}
In Python, all ways rubbish resulted:
print lib.test_ret_float()
>>1074161254
print c_float(lib.test_ret_float()).value
>>1074161280.0
In case of int
all works fine.
It seems, that type conversation doesn't work as expected and really returns raw
4byte value that converts not to float
but int
, why?
Upvotes: 2
Views: 3393
Reputation: 21
I know it is way too late but to whoever searches this and might be looking to the same issue I had.
Usage: if you passed a pointer to a variable as and argument and the C function changes replaces it with a floating point, this way you can repackage the python interpretation (integer) value to a signaled 32bit floating point
def ieee754(value):
"""Repackages values to 32bit floating point"""
packed_v = struct.pack('>L', value)
return struct.unpack('>f', packed_v)[0]
Upvotes: 2
Reputation: 1413
The problem was that I missed restype
to setup:
lib.test_ret_float.restype = c_float
That solves the problem
Upvotes: 5