embedding problem with dictionary
Howard Lightstone
howard at eegsoftware.com
Thu Jul 18 16:13:33 EDT 2002
I am using a mixed C(++)/Python program to process some real-time data.
The Python part (2.0 in my case) handles the GUI, operator selections, etc.,
and the C part does the real-time (at least as good as W-ants-to-do-whatever
-it-wants-INDOWS will let it).
I build a dictionary in my C code which contains some other dictionaries
and pass it from an embedded Python extension to a C routine (which actually
runs the real-time part). I am able to use all the parts of this dictionary
(getdict).
However, I now need to pass back some values to the Python code (through
the dictionary) using putdict(). I seem to be getting intermittent results
here. Sometimes the values are unchanged from passed-in values and
sometimes they work.
Am I not doing what I think I am?
Interface routines:
(idict is the dictionary object passed in from Python to C++)
static int
getdictstring(char *basename,char *key,char *dest,int destlen,int forceabort)
{
char *d=basename,dn[200],*buffer;
PyObject *pnr,*pnd,*pnt;
int slen;
if (!basename)
d="";
// find correct "dict"
pnd=idict;
if (*d) // is the the base dictionary or a dictionary object
{
pnd=PyDict_GetItemString(idict,basename); // borrowed reference
if (!pnd)
{
if (forceabort)
{
sprintf(dn,"bad subdict : %.50s",basename);
raise_fatal_error(dn);
}
else
return 1;
}
}
pnr=PyDict_GetItemString (pnd, key); // borrowed reference
if (!pnr)
{
if (forceabort)
{
sprintf(dn,"bad key name %.50s : %.50s",basename ? basename:"",key);
raise_fatal_error(dn);
}
else
return 2;
}
pnt=PyObject_Str(pnr); // new ref
if (PyString_AsStringAndSize (pnt, &buffer, &slen) < 0)
{
raise_fatal_error("asStringAndSize");
}
if (slen >= destlen)
slen=destlen-1;
memcpy(dest,buffer,slen);
dest[slen]=0;
Py_DECREF(pnt); // remove "new" ref
return 0;
}
#if 1
int
putdict(char *basename,char *key,char *value)
{
char *d=basename;
PyObject *pnd,*pnt;
if (!basename)
d="";
// find correct "dict"
pnd=idict;
if (*d) // is it the base dictionary or an object in it
{
pnd=PyDict_GetItemString(idict,basename); // borrowed reference
if (!pnd)
{
// must "create" such a subdictionary
pnd=PyDict_New(); // new reference
// add reference into main dict
PyDict_SetItemString(idict,basename,pnd);
// always leave with valid pnd
}
}
// create the 'string' object
pnt=PyString_FromString(value); // new reference ...leave it around
PyDict_SetItemString(pnd,key,pnt); // if this replaces something (as is usual)
// python handles ref counts
return 0;
}
#endif
More information about the Python-list
mailing list