On 06/15/2010 10:51 PM, Andy Jost wrote: > Hi, > > > > I’m working on an application program that embeds Python using the > C-API. Sometimes, I need to call functions written in pure Python from > the C code, so I use Py_CompileString and PyEval_EvalCode.
I'd recommend putting your Python code in a module that your C code can import. You can let the interpreter itself take care of compiling the code, and call out from C to Python with PyImport_ImportModule, PyObject_GetAttrString, PyObject_Call, and functions like that. > > > I would like to avoid compiling the same code over and over by storing > the result of Py_CompileString in a static variable, however, the > application does sometimes restart the Python interpreter. > > My question: is the PyCodeObject * returned from Py_CompileString still > valid after Python is restarted? The short answer is: no. You usually handle just a pointer. I'd expect that the interpreter frees all objects on shutting down, so your pointer would no longer be valid. (then again, this is pure guesswork). You could probably deep-copy the code struct itself, but it's probably not worth the hassle. If using a module as I suggested above isn't an option for some obscure reason, you can always marshal (or pickle) the code -- then it can certainly outlive the interpreter. Thomas -- http://mail.python.org/mailman/listinfo/python-list