Jan Gimmler
Jan Gimmler

Reputation: 43

Python ctypes - TypeError: int expected instead of float

I try to convert a python list to a ctype array. But somehow I always get the error "TypeError: int expected instead of float" in the line with this code:

    self.cValues = (ctypes.c_int * len(self.values))(*self.values)

I created self.values a few lines before. It's a normal python list. I am 100% sure, len(self.values) is an integer, I tested it with the type() function and the result was class 'int'. So what else is the problem with this line? Thanks for help.

Upvotes: 1

Views: 4328

Answers (1)

Josh Kupershmidt
Josh Kupershmidt

Reputation: 2710

The problem is not with the len() function but with self.values being a List of floats not a List of ints. Try it with a small self-contained example to see:

import ctypes
values = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
cValues = (ctypes.c_int * len(values))(*values)

bombs out with the "TypeError: int expected instead of float" message you got. If you change values to be ints, i.e. values = [0, 1, 2, 3, 4, 5] it works fine. Or, since you say in your last comment that self.values is a List of floats, you probably want to use ctypes.c_float like so:

values = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
cValues = (ctypes.c_float * len(values))

Upvotes: 2

Related Questions