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

Stefan Seefeld seefeld at sympatico.ca
Sun Nov 12 17:34:29 CET 2006


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

-- 

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



More information about the Cplusplus-sig mailing list