[C++-sig] Calling member function of object created in C++ via embedded Python

Ron Brown, Jr. rbrown at gamry.com
Wed Apr 18 17:58:49 CEST 2007

I'm still having quite a bit of trouble wrapping my mind around this 
problem, and feel like I'm just missing something obvious.  Again, what 
I'm trying to do is have an instance of an object in C++ and call one of 
that particular object's member functions from Python.

In the example below, I create an instance of the "World" class on the 
C++ side.  It's then COPIED into a new object on the Python side.  This 
is not how I want my application to behave.  How can I change this 
example so that Python doesn't create a NEW object and copy it, but 
instead uses the object created by C++?

I read through the documentation on "ptr()", but I'm not really sure how 
to apply that to this problem.

I'm still quite new to both Python and Boost.Python, so please keep that 
in mind.  Thanks again!


#include <boost/python.hpp>
#include <iostream>
using namespace boost::python;

class World
      void set(std::string msg) { this->msg = msg; }
      std::string greet() { return msg; }
      std::string msg;

          .def("greet", &World::greet)
          .def("set", &World::set)

int main(int argc, char *argv[])


	World worldObject, worldObject2;
	worldObject.set("Hello from C++!");

	try {
		PyRun_SimpleString("import hello");
		object module(handle<>(borrowed(PyImport_AddModule("__main__"))));
		object dictionary = module.attr("__dict__");
		dictionary["pyWorldObject"] = worldObject;
		PyRun_SimpleString("pyWorldObject.set('Hello from Python!')");
		object resultObject = dictionary["pyWorldObject"];
		worldObject2 = extract<World>(resultObject);
	} catch (error_already_set) {
	std::cout << "worldObject.greet(): " << worldObject.greet() << std::endl;
	std::cout << "worldObject2.greet(): " << worldObject2.greet() << std::endl;
	return 0;
worldObject.greet(): Hello from C++!
worldObject2.greet(): Hello from Python!

More information about the Cplusplus-sig mailing list