tags:

views:

305

answers:

1

I've tried to replace

PyRun_SimpleString("import Pootle");

with

PyObject *obj = PyString_FromString("Pootle");
PyImport_Import(obj);
Py_DECREF(obj);

after initialising the module Pootle in some C code. The first seems to make the name Pootle available to subsequent PyRun_SimpleString calls, but the second doesn't.

Could someone please explain the difference to me? Is there a way to do what the first does with C API calls?

Thanks

+2  A: 

All the PyImport_Import call does is return a reference to the module -- it doesn't make such a reference available to other parts of the program. So, if you want PyRun_SimpleString to see your new imported module, you need to add it manually.

PyRun_SimpleString works automatically in the __main__ module namespace. Without paying a lot of attention to error checking (be wary of NULL returns!), this is a general outline:

PyObject *main = PyImport_AddModule("__main__");  
PyObject *obj = PyString_FromString("Pootle");
PyObject *pootle = PyImport_Import(obj);  
PyObject_SetAttrString(main, "Pootle", pootle);  

Py_DECREF(obj);
Py_XDECREF(pootle);
ffao