Instantiating and initialising C++ with embedded Python

Martin v. Löwis loewis at
Tue Sep 17 22:42:50 CEST 2002

Morfeas <greek_bill at> writes:

> 1. My main program is in C++, so I need to embed the python interpreter.


> 2. I need to allow python access to my C++ classes, therefore I need to 
> extend the embedded interpreter.


> a) a brief description of the whole process

You need to provide two things:

- modules that expose "core" functions of your API,
- Python "types" that encapsulate your C++ objects.

The Python interpreter has a global table of all available modules,
Modules/config.c:_PyImport_Inittab. This table lists entry points for
all "builtin" modules. You need to compose a table that has all the
"standard" builtin modules you want to use in your scripts, plus any
extension modules that you implement yourself.

In addition, to wrap C++ objects, you need to define "type objects",
which are structures that essentially contain function pointers to the
"virtual method tables" of a Python type; associated with such a type
is a C structure that defines the layout of actual instances of the

> b) some code examples

See Modules/xxmodule.c for an example of an extension module; I
recommend to also read the "Embedding and Extending" tutorial.

> c) suggestions about useful tools

I'd recommend to write all the necessary code by hand. People will
suggest various tools, specifically:

- SWIG, which can generate wrappers around existing APIs,
- CXX, which exposes the Python API in a C++-ish way,
- Boost Python, to wrap C++ libraries.


More information about the Python-list mailing list