Setting a C-structure from Python
Armin Steinhoff
Armin at Steinhoff_de
Thu Jul 6 15:06:17 EDT 2000
Hello!
In article <39649D5C.F1652171 at seatech.fau.edu>, bdupire says...
>
>I already posted this message on www.deja.com but as it doesn't appear
>in the newsgroup, I repost it here.
>
>My aim is to write an extension module to access functions in C which
>"get" and "set" some structures from/in shared memory.
>
> In order to do this, I implemented the following programs:
> * structure.py
> * test_API.c
>
> It works well when I set the structure the first time, but not a second
>time I have got the following (run-time) error... did I miss something?
Just a proposal: set CFLAGS to -g -Od, make clean, make, wd python and
set a break point in your module ... then you got the changes to see the
details.
>
>
> >>> import structure
> The structure is now:
> name Benoit
> age 22
> rate 3.141500
>
>
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> File "structure.py", line 19, in ?
> test_API.setstruct(packed)
> TypeError: argument 1: expected string,
> found
Strange ... check the LDFLAGS in ./Modules and increase the stack size by
-N128k (128kB) e.g. .... 32k is probbably not enough.
>
>
>
>
> I am working with Python 1.5.2 on QNX 4.25
>test_API.c is therefore statically linked with Python as dynamic
>linking is not possible on QNX.
>
>
>
> file : structure.py
> -----------------------------------------
>
> import struct
> import test_API
>
> #1st try
> fmt="20sif"
> a="Benoit"
> b=22
> c=3.1415
> packed=struct.pack(fmt,a,b,c)
> test_API.setstruct(packed)
>
> #2nd try
> a="Ben"
> b=23
> c=3.1417
> packed=struct.pack(fmt,a,b,c)
> test_API.setstruct(packed)
>
>
> file: test_API.c
> --------------------------------------
> #include <stdio.h>
> #include "Python.h"
>
> typedef struct{
> char name[20];
> int age;
> float rate;
> } examplestruct;
>
>
> examplestruct * example;
>
>
> static void print_struct()
> {
> printf("The structure is now: \n");
> printf("name %s\n",example->name);
> printf("age %i\n",example->age);
> printf("rate %f\n", example->rate);
> }
>
>
> static PyObject * test_setstruct(PyObject * self, PyObject * args) {
> PyObject * string_from_python;
>
> if (!PyArg_ParseTuple(args,"S",&string_from_python)) return NULL;
>
> example= (examplestruct *) PyString_AsString(string_from_python);
>Py_DECREF(string_from_python);
> print_struct();
>
> Py_INCREF(Py_None);
> return Py_None;
> }
>
>
> static PyObject * test_getstruct(PyObject * self, PyObject * args) {
> /* if there are any arguments */
> if (!PyArg_NoArgs(args))
> return NULL;
> return PyString_FromString(example);
Py_DECREF removes that object ... so it is not clear what 'example' is
referencing in 'test_getstruct'.
Greetings
Armin
More information about the Python-list
mailing list