Setting a C-structure from Python

Benoit Dupire bdupire at seatech.fau.edu
Fri Jul 14 15:04:41 EDT 2000


Armin wrote:
--------------------------------------------------------------

 I have changed your code in the following way:

 static PyObject * test_setstruct(PyObject * self, PyObject * args) {
 //PyObject * string_from_python;

 char * string_from_python;
 int len;

 // if (!PyArg_ParseTuple(args,"S",&string_from_python)) return NULL;
 if (!PyArg_ParseTuple(args,"s#",&string_from_python, &len)) return NULL;

 // example= (examplestruct *) PyString_AsString(string_from_python);
example= (examplestruct *) string_from_python;

 // Py_DECREF(string_from_python);
 print_struct();

 Py_INCREF(Py_None);
 return Py_None;
 }
 ----------------------------------------------------

Ok it works too! You convert the PythonString in a C string representation
right away with PyArgs_ParseTuple.



Now, I changed the test_getstruct function in the same way..

static PyObject * test_getstruct(PyObject * self, PyObject * args)
{
 if (!PyArg_ParseTuple(args,"")) return NULL;
 return Py_BuildValue("s",(char *)exampleptr);
}


Yes.. it was too easy : it doesn't work :
    Traceback (innermost last):
      File "<stdin>", line 1, in ?
      File
"//1/old_home/bdupire/Alpha/morpheus/Python-1.5.2/Lib/my_prog/structure.py",
line 24, in ?
       a =struct.unpack(fmt,rec)
struct.error: unpack str size does not match format

So my question is the following: how to tell Py_BuildValue about the size of
the structure and the number of bytes to grab ?




More information about the Python-list mailing list