[Tutor] NEWBIE: init a multiple field C struct from Python easyily

Edward Tsang ed_tsang@yahoo.com
Fri, 17 Sep 1999 11:45:07 -0700 (PDT)


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;
 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);
 }
__________________________________________________
Do You Yahoo!?
Bid and sell for free at http://auctions.yahoo.com