1

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.

Jan Gimmler
  • 33
  • 1
  • 8
  • 3
    Look at what you pasted here again... it's not even a valid expression. – Jeff Mercado Aug 27 '14 at 01:05
  • @JeffMercado How do you mean that? I did it like in here: http://stackoverflow.com/questions/4145775/how-do-i-convert-a-python-list-into-a-c-array-by-using-ctypes Or do you mean the selfs? – Jan Gimmler Aug 27 '14 at 01:11
  • Ok, saw the mistake, I removed it. Sorry for that, copy & paste fail. But that problem is still the same. – Jan Gimmler Aug 27 '14 at 01:15
  • 1
    I am suspicious about what self.values really contains: can you print out its repr()? For instance, if values is a List of ints, your expression would work fine: `values = [0,1,2,3,4,5]; cValues = (ctypes.c_int * len(values))(*values)`. But if values is a List of floats, or ints mixed with floats, etc. it will bomb out: `values = [0,1.0,2,3,4,5]; cValues = (ctypes.c_int * len(values))(*values)` gets the same error you posted. – Josh Kupershmidt Aug 27 '14 at 01:21
  • There actually are floats in the list. I thought the problem would be the len() function. Is there a way to make a ctype array with floats? I won't print out the repr, because the array is a 100000 lines 3D object coord array ^^ – Jan Gimmler Aug 27 '14 at 01:27

1 Answers1

2

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))
Josh Kupershmidt
  • 2,112
  • 15
  • 29