[C++-sig] Creating a python class from c++

Stefan Seefeld seefeld at sympatico.ca
Wed Nov 15 14:39:33 CET 2006


James Healey wrote:
>> James Healey wrote:
>>> Can any body tell me how you create a python class
>>> from within c++?
>>>
>>> so in my .py file I have 
>>>
>>> class MyClass:
>>>    def f(self):
>>>       return 'hello world'
>>>
>>>
>>> And from my c++ code i want to be able to do....
>>>
>>> x = new MyClass
>>> x.f()
>> namespace bpl = boost::python;
>> bpl::dict global;
>> bpl::exec_file("your_file.py", global, global);     
>> // load the definition
>> bpl::object my_class = global["MyClass"];           
>> // extract the new type
>> bpl::object my_instance = my_class();               
>> // instantiate it
>> bpl::object retn = my_instance.attr("f")();         
>> // call it
>> std::string value = bpl::extract<std::string>(retn);
>> // extract return value
>>
>> HTH,
>> 		Stefan
> 
> I dont seem to have the exec_file command in my
> current boost build, I'm using 1.33.1 which was
> downloaded via the boost website.

True, it has been added to boost.python sometime 2005,
but unfortunately didn't make it into the 1.33 release.

If you can't wait a current snapshot, you can take a
verbatim copy of the function:

// Execute python source code from file filename.
// global and local are the global and local scopes respectively,
// used during execution.
object BOOST_PYTHON_DECL exec_file(str filename, object global, object local)
{
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *f = python::extract<char *>(filename);
  // Let python open the file to avoid potential binary incompatibilities.
  PyObject *pyfile = PyFile_FromString(f, "r");
  if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file");
  python::handle<> file(pyfile);
  PyObject* result = PyRun_File(PyFile_AsFile(file.get()),
                f,
                Py_file_input,
                global.ptr(), local.ptr());
  if (!result) throw_error_already_set();
  return object(detail::new_reference(result));
}

HTH,
		Stefan


-- 

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



More information about the Cplusplus-sig mailing list