[C++-sig] PyCode_New and new.code() functions

Stefan Seefeld seefeld at sympatico.ca
Mon Sep 11 15:24:14 CEST 2006


anders langlands wrote:

> boost::python::exec sounds like exactly what I want... but I can find no
> documentation for this either, do you have I link? Nor can I find it in any
> of the boost::python headers. we're using boost 1_33_1 here at the moment.

Ah, well, I added it after the 1_33_1 release. It will be included in the 1_34
release (in case that is of any help).

However, the implementation is really simple, so you may as well include the
code directory:


namespace boost
{
namespace python
{
object exec(str string, object global, object local)
{
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *s = python::extract<char *>(string);
  PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr());
  if (!result) throw_error_already_set();
  return object(detail::new_reference(result));
}
}
}

This executes 'string' in the context of 'global' and 'local'. The latter two
are (potentially empty) dictionaries. Once execution has successfully terminated,
'global' will contain whatever objects 'string' injected into them such as type definitions
and other objects. You can then extract these from 'global' and call them from C++.
See for example
http://boost.cvs.sourceforge.net/*checkout*/boost/boost/libs/python/test/exec.cpp?revision=1.5.2.1

HTH,
		Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list