setting a C-structure from Python
tidop at my-deja.com
tidop at my-deja.com
Wed Jul 5 21:46:37 EDT 2000
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... where is the bug ?
>>> 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
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);
}
/*************************************************************
METHOD REGISTRATION TABLE
List of functions defined in the module
*************************************************************/
static struct PyMethodDef test_API_methods[] = {
{"setstruct", test_setstruct, 1},
{"getstruct", test_getstruct, 1},
{NULL, NULL}
};
/*************************************************************
Initialization function
*************************************************************/
void inittest_API()
{
PyObject *m, *d;
/*create the module and add the functions */
m= Py_InitModule("test_API", test_API_methods);
/* add symbolic constants to the module */
d= PyModule_GetDict(m);
if (PyErr_Occurred())
Py_FatalError("can't initialize module test_API\n");
}
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list