boost::python sharing native c++ object with python

Joerg Sauer NeXTStep at
Fri Aug 24 19:38:00 CEST 2001

hopefully the subject is attracting!?

I know how to create an extension module using boost and how to make a
class wrapper using python::class_builder. That works fine!

Now that I have an extension DLL I want to embed python in my

How can I create an c++ class object in the c++ app and export this
object to the python instance (not as function parameter but as object
at global or module level)?

Suggest I have 

 class DLLAPI myclass 
	void setval(int x){_x=x;}
	int   getval(){return _x;}
	int _x;

#include "myclass.h"
python::module_builder this_module("mymod");

    // Create the Python type object for our extension class.
    python::class_builder<myclass> myclass_class(this_module,

    myclass_class.def(&myclass::setval, "setval");
    myclass_class.def(&myclass::getval, "getval");

now I have a main programm
#include <iostreams>
#include <Python.h>
#include "myboostmod.h" //???? or just #include "myclass.h"
using std::cout;

int main(int argc, char** argv)
	PyObject *pMod, *pDict, *pObject;

	pMod = PyImport_ImportModule("mymod");

	// Now that I have python up and ready, I want to export a c++
	// class
	myclass mc1;
	// I would like to export this object with the python name mc1
	// too 
-->>> export mc1 to python with name mc1.
	// Now I want to run a simple python statement

	PyRun_SimpleString("print mc1.getval()");
	PyRun_SimpleString("print mc1.setval(12345)");

	// here the object should keep the value set in python
	cout << "Now mc1 is:" << mc1.getval() << "\n";


Does anybody has a sollution or some hints?

Thanks in advance 

More information about the Python-list mailing list