Embedding: Problem with CallObject
James Turner
jamwt at jamwt.com
Wed Jun 13 20:49:05 EDT 2001
Hello.
I'm just starting to play with embedding Python in C, and I'm getting a
huge headache from trying to figure out what's wrong with my code here:
--test.c--
#include <Python.h>
int main(int argc, char** argv)
{
PyObject *str,*mod,*flist,*func,*args;
Py_Initialize();
str = PyString_FromString("anything");
/*Import mod */
mod = PyImport_Import(PyString_FromString("one") );
flist = PyModule_GetDict(mod);
func = PyDict_GetItemString(flist,PyString_FromString("out"));
args = PyTuple_New(1);
PyTuple_SetItem(args, 0,str);
/* FAILS HERE!! */
PyObject_CallObject(func,args);
Py_XDECREF(flist);
Py_XDECREF(func);
Py_XDECREF(args);
Py_XDECREF(mod);
Py_XDECREF(str);
Py_Finalize();
return 0;
}
--one.py--
def out(str):
print "C says: %s" % str
--end code--
And, right where I've commented FAILS HERE!! in the C code, I get the
lovely:
Segmentation fault (core dumped)
I one.py is in the current directory, so I run it
$env PYTHONPATH=. ./test
It imports the module fine, and I can successfully run out(str) if I
change it to out() and pass it NULL from C. (Meaning call the func w/no
arguments and just print "Hello World" or something.)
After testing this with:
if (PyErr_Occurred())PyErr_Print();
all over the C code, I'm pretty sure this is why it's failing: I'm doing
something wrong with the way I'm passing it that tuple from C.
Hopefully someone more skilled can lend a hand!
Thanks, James
(PS) -- I am aware of CallMethod with the formatted string... I'm looking
for a solution that enables one.py to modify my C-made PyObjects. My
code is based on learning from http://www.mcmillan-inc.com/embed.html
and referring to the official Python/C Api @ www.python.org.
More information about the Python-list
mailing list