[C++-sig] Evaluating multiple statements

Murray Cumming murrayc at murrayc.com
Wed Jul 7 14:00:10 CEST 2004

On Tue, 2004-07-06 at 21:45 +0200, Ingo Luetkebohle wrote:
> Hi Murray,
> you're using Py_CompileString already and that method can compile whole
> modules with Py_file_input.
> Say you have
> 	def fun():
> 		return 1	
> Where 'fun' could of course be arbitrarily complex.  Then you'd do
> something like (all error handling and reference counting omitted):
> 	PyObject* c = Py_CompileString(text, "null", Py_file_input);
> 	PyObject* module = PyImport_ExecModule("module name", c);
> 	PyObject* dict = PyModule_GetDict(module);
> 	PyObject* f = PyDict_GetItemString(dict, "fun");
> And you get yourself a callable for "fun" for use with
> PyObject_CallObject.

Yes, that's what I ended up doing. I build a function definition from
the supplied statements, execute it so that it's defined, then evaluatea
call to that function. It seems to work really well.

Murray Cumming
murrayc at murrayc.com

More information about the Cplusplus-sig mailing list