[Tutor] converting a Python var to a C-type

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 3 Apr 2001 00:46:25 -0700 (PDT)


On Mon, 2 Apr 2001, Benoit Dupire wrote:

> the type the C side would accept is contained in a Python string
> variable:
> examples: "int", "short", "double", "float", "ulong", "uint", "ushort",
> "ubyte", "char"..

I'm not quite sure if this will help, but the struct module has a nice
function calcsize() which will calculate how large a type will be:

    http://python.org/doc/current/lib/module-struct.html

and the rest of the module itself might be very useful, since it does deal
with C-style variables.  pack() and unpack(), too, sound relevant.

I'm not quite sure what you mean by "fit"; do you mean "fit" by the size
of the structure, or range?  One way I can see about doing this is with a
data-directed programming style: keep a dictionary that matches
desired_types with your stubs:

    type_funcs = { 'int' : convertInt,
                   'ushort' : convertShort,
                   ...
                 }

This becomes useful because we can later do a:

    func = type_funcs[desired_type]
    return func(value)

and have each of your conversion functions take responsibility for either
converting things or raising ValueErrors.  It makes it easier to add new
times as you experiment because it involves just adding another element to
your dictionary.

There's probably a better way to do this, but I'm getting sleepy at the
moment.  *grin*

Anyway, hope this helps!