Re: [ctypes-users] Testing for an array type of unknown length
Brought to you by:
theller
From: Terry G. <te...@ax...> - 2003-09-29 19:50:04
|
Thomas Heller <th...@py...> writes: > "Terry Griffin" <te...@ax...> writes: > >> Greetings, >> >> If I have a structure: >> >> class MyStruct(Structure): >> _fields_ = [(whatever... >> >> Then I can do this: >> >> mystructdata = MyStruct() >> >> if type(mystructdata) == MyStruct: >> operate on mystructdata >> else: >> raise TypeError,... >> >> Fine so far. Now say I want my 'if' construct is to support both >> singletons and arrays using logic like this: >> >> MyStructArray = MyStruct * 10 # or some other size >> mystructdata = MyStructArray() >> >> if type(mystructdata) == MyStruct: >> operate on mystructdata, the singleton >> elif type(mystructdata) is an array of MyStruct of unknown length: >> alen = len(mystructdata) >> operate on mystructdata, an array of MyStruct of length 'alen' >> else: >> raise TypeError,... >> >> How do I do 'elif' condition? > > First possibility is this one: > > elif type(mystructdata[0]) == MyStruct: > > But it doesn't work for simple types like c_int for example, because > indexing an array of c_int items gets you normal Python integers, not > c_int instances. > > And the second one is to use the undocumented _type_ attribute: > > elif type(mystructdata)._type_ == MyStruct: > > Thomas > The first option crossed my mind, but it could be fooled if mystructdata was a list, tuple, or other container with an iterator. Some preliminary checks for ListType etc could catch those. The second method would raise an exception if mystructdata was not a ctypes array at all, which in my case is probably ok since I was going to raise an exception on a type mismatch anyway. Anyone know if there any plans for a general (and documented) solution for this in future versions of ctypes? Thanks, Terry -- Terry Griffin Axian Inc. http://www.axian.com/ |