CTYPES structure passing

Bryan bryanjugglercryptographer at yahoo.com
Thu Jun 3 22:03:46 EDT 2010


Peter West wrote:
> I'm hoping someone here can tell me what I'm doing wrong as I've spent
> the best part of three days reading docs and trying code.

Yeah, I imagine a person could re-read them over and over and not see
the gotcha. Sit down, maybe prepare some comfort food, and try to to
be to upset when you find out how your three days were wasted...

[...]
> In my Python code I have
>
> #------------- Frame format --------------------
> class FRAME_FORMAT_UNION(Union):
>     __fields__ = [("subSample", c_ushort),  #  sub-sample ratio in x
> direction in pixels (x:1)
>                  ("binning", c_ushort )]    #  binning ratio in x
> direction in pixels (x:1)
>
> class LUCAM_FRAME_FORMAT(Structure):
>    __fields__ = [( "xOffset", c_ulong),  # x coordinate on imager of
> top left corner of subwindow in pixels

There's your problem: The all-important _fields_ attribute is spelled
with *single* underscores. You're probably familiar with the Python
convention of special member names with double-underscores at each
end? Well, ctypes doesn't follow it.

[...]
> and make the call like this
>
>   FrameRate = c_float(0)
>   FrameFormat = LUCAM_FRAME_FORMAT()
>
>   FrameFormat.xOffset = 0
>   FrameFormat.yOffset = 0
>   FrameFormat.width = 0
>   FrameFormat.width = 0
>   FrameFormat.height = 0
>   FrameFormat.pixelFormat = 0
>   FrameFormat.XUnion = 0
>   FrameFormat.flagsX = 0
>   FrameFormat.YUnion = 0
>   FrameFormat.flagsY = 0


Which gives your FrameRate object some new attributes, completely
unrelated to the _fields_ that ctypes uses to lay out a struct.

Rhodri James pointed out that you want:

    FrameFormat.XUnion.subSample = 0
or
    FrameFormat.XUnion.binning = 0

And same for FrameFormat.YUnion. If you spell _fields_ as ctypes
requires, it will complain about your assignments, in that you are
trying to assign an in to a union. As your code is, those assignments
just make a new attribute to which you can assign anything.

--
--Bryan



More information about the Python-list mailing list