Embedding Python

If you have an application already written in C or C++ (or another classic compiled language), you may want to embed Python as your application’s scripting language. To embed Python in languages other than C, the other language must be able to call C functions. In the following, I cover only the C view of things, since other languages vary widely regarding what you have to do in order to call C functions from them.

Installing Resident Extension Modules

In order for Python scripts to communicate with your application, your application must supply extension modules with Python-accessible functions and classes that expose your application’s functionality. If these modules are linked with your application, rather than residing in dynamic libraries that Python can load when necessary, register your modules with Python as additional built-in modules by calling the PyImport_AppendInittab C API function.

PyImport_AppendInittab

int PyImport_AppendInittab(char* name,void (*initfunc)(void))

name is the module name, which Python scripts use in import statements to access the module. initfunc is the module initialization function, taking no argument and returning no result, as covered in Module Initialization (i.e., initfunc is the module’s function that would be named initname for a normal extension module in a dynamic library). PyImport_AppendInittab must be called before Py_Initialize.

Setting Arguments

You may want to set the program name and arguments, which Python scripts can ...

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.