C API for modules

John Machin sjmachin at lexicon.net
Wed Mar 27 06:16:45 EST 2002


"Edward C. Jones" <edcjones at erols.com> wrote in message news:<3CA1499D.4070802 at erols.com>...
> John Machin wrote:
> > "Edward C. Jones" <edcjones at erols.com> wrote in message news:<3CA09F43.80206 at erols.com>...
> > 
> >>Is there some simple way to call functions in modules from C? In 
> >>particular, for module struct, how do I call pack, unpack, and calcsize?
> >>
> > 
> > 
> > OK, I'll be the bunny and ask the obvious(?) meta-question:
> > 
> > Give that the struct module is designed for Python callers to
> > pack/unpack C structs (laboriously), why bother? Why not just
> > manipulate the structs in C??
> 
> So I should use PyString_FromStringAndSize in C and struct.unpack in 
> Python or struct.pack in Python and PyString_AsStringAndSize in C.

Clarifying your "or":

Possible to use [PyString_FromStringAndSize in C and struct.unpack in 
Python] to pass data from C to Python AND [struct.pack in Python and
PyString_AsStringAndSize in C] to pass data from Python to C.

Just get check, re-check and re-re-check your format strings.

Yes, you sure don't need to call Python's struct.anything() from C,
especially struct.calcsize -- just spell it "sizeof" :-)

The struct module is designed for Python callers who have to interact
with C structs over whose format and layout the Python callers have no
control -- for example data in a binary file.

As you seem to be in control of both the Python side and the C side,
you may have more flexibility. If I didn't already have lots of C code
expecting the data to be in a particular struct, and there were only a
few fields involved, I'd be inclined to use Py_BuildValue to send data
from C to Python and PyArg_{Parse|Unpack}Tuple to get data from Python
-- in other words, the normal argument passing and return-value
mechanism. For a large/variable number of items of the same type, the
array module would be indicated.

Cheers,
John



More information about the Python-list mailing list