[Tutor] NEWBIE: init a multiple field C struct from Python easyily
Michael P. Reilly
arcege@shore.net
Fri, 17 Sep 1999 17:13:22 -0400 (EDT)
Edward, I think it may be time to move this level of questioning to the
Python list (mailto:python-list@python.org or news:comp.lang.python), or
to the respondants directly. :)
See my comments below.
-Arcege
> Hey, I am trying to initialise a C structure from Python.
> My Aim is to init a C structure without passing each indivual elements
> through the interface, but rather package the whole thing and pass that
> it one time. Then the C may do somethign about it, initialise its won
> struct and pass back a struct with the same kind of elements but with
> different parameters. I am stuck with the intialising the C struct
> part, and have not clue how to convert the C struct back to a PyObject
> appropriate to pass back to the Python script. Please help . Below is
> the code.
>
> Error: segmentation fault occurres at
> PyArg_ParseTuple(args,"s:mymath",string_from_Python))
> PyString_Size(string_from_Python)calls inside
> function pyfunc_mystruct
>
> Here is what I tried:
>
> >From the python script I have:
> import struct
> import mymath_wrapper
> fmt = "120sf"
> a=255
> b='knights who say ni'
> c=3.14159011841
> data = struct.pack(fmt,a,b,c)
> mymath_wrapper.mystruct(data)
>
> in my mymath_wrapper.c file I have:
> #include <Python.h>
> #include "mymath.h"
>
> PyObject*
> pyfunc_mystruct(self, args)
> PyObject *self, *args;
> {
> PyObject* string_from_Python;
> if(!PyArg_ParseTuple(args,"s:mymath",string_from_Python))
> return NULL;
Using a small "s" returns a (char *), using a capital "S" returns a
(PyObject *).
The segmentation fault is from attempting to access a character array
as the fields of a PyObject *.
> if(PyString_Size(string_from_Python)!= sizeof(struct diffstruct))
> {
> PyErr_SetString(PyExc_AssertionError, "Given strgin not a good
> size");
> return NULL;
> }
>
>
> globaldiffstruct = (diffstruct
> *)PyString_AsString(string_from_Python);
>
> printf("globaldiffstruct calling within C:%d %s
> %f\n",globaldiffstruct->a, globaldiffstruct->b,globaldiffstruct->c);
> /* python side will print the last res value*/
> return string_from_Python; /* not correct, deal with this later */
> }
>
> static PyMethodDef mymathMethods[] =
> {
> {"mystruct", pyfunc_mystruct, 1},
> {NULL,NULL}
> };
>
> void initmymath_wrapper()
> {
> (void) Py_InitModule("mymath_wrapper", mymathMethods);
> }
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------