Extending/Embedding FAQ

Can I create my own functions in C?

Yes, you can create built-in modules containing functions, variables, exceptionsand even new types in C. This is explained in the documentExtending and Embedding the Python Interpreter.

Most intermediate or advanced Python books will also cover this topic.

Can I create my own functions in C++?

Yes, using the C compatibility features found in C++. Placeextern"C"{...} around the Python include files and putextern"C" before eachfunction that is going to be called by the Python interpreter. Global or staticC++ objects with constructors are probably not a good idea.

Writing C is hard; are there any alternatives?

There are a number of alternatives to writing your own C extensions, dependingon what you’re trying to do.Recommended third party toolsoffer both simpler and more sophisticated approaches to creating C and C++extensions for Python.

How can I execute arbitrary Python statements from C?

The highest-level function to do this isPyRun_SimpleString() which takesa single string argument to be executed in the context of the module__main__ and returns0 for success and-1 when an exception occurred(includingSyntaxError). If you want more control, usePyRun_String(); see the source forPyRun_SimpleString() inPython/pythonrun.c.

How can I evaluate an arbitrary Python expression from C?

Call the functionPyRun_String() from the previous question with thestart symbolPy_eval_input; it parses an expression, evaluates it andreturns its value.

How do I extract C values from a Python object?

That depends on the object’s type. If it’s a tuple,PyTuple_Size()returns its length andPyTuple_GetItem() returns the item at a specifiedindex. Lists have similar functions,PyList_Size() andPyList_GetItem().

For bytes,PyBytes_Size() returns its length andPyBytes_AsStringAndSize() provides a pointer to its value and itslength. Note that Python bytes objects may contain null bytes so C’sstrlen() should not be used.

To test the type of an object, first make sure it isn’tNULL, and then usePyBytes_Check(),PyTuple_Check(),PyList_Check(), etc.

There is also a high-level API to Python objects which is provided by theso-called ‘abstract’ interface – readInclude/abstract.h for furtherdetails. It allows interfacing with any kind of Python sequence using callslikePySequence_Length(),PySequence_GetItem(), etc. as wellas many other useful protocols such as numbers (PyNumber_Index() etal.) and mappings in the PyMapping APIs.

How do I use Py_BuildValue() to create a tuple of arbitrary length?

You can’t. UsePyTuple_Pack() instead.

How do I call an object’s method from C?

ThePyObject_CallMethod() function can be used to call an arbitrarymethod of an object. The parameters are the object, the name of the method tocall, a format string like that used withPy_BuildValue(), and theargument values:

PyObject*PyObject_CallMethod(PyObject*object,constchar*method_name,constchar*arg_format,...);

This works for any object that has methods – whether built-in or user-defined.You are responsible for eventuallyPy_DECREF()‘ing the return value.

To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming thefile object pointer is “f”):

res=PyObject_CallMethod(f,"seek","(ii)",10,0);if(res==NULL){...anexceptionoccurred...}else{Py_DECREF(res);}

Note that sincePyObject_CallObject()always wants a tuple for theargument list, to call a function without arguments, pass “()” for the format,and to call a function with one argument, surround the argument in parentheses,e.g. “(i)”.

How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?

In Python code, define an object that supports thewrite() method. Assignthis object tosys.stdout andsys.stderr. Call print_error, orjust allow the standard traceback mechanism to work. Then, the output will gowherever yourwrite() method sends it.

The easiest way to do this is to use theio.StringIO class:

>>>importio,sys>>>sys.stdout=io.StringIO()>>>print('foo')>>>print('hello world!')>>>sys.stderr.write(sys.stdout.getvalue())foohello world!

A custom object to do the same would look like this:

>>>importio,sys>>>classStdoutCatcher(io.TextIOBase):...def__init__(self):...self.data=[]...defwrite(self,stuff):...self.data.append(stuff)...>>>importsys>>>sys.stdout=StdoutCatcher()>>>print('foo')>>>print('hello world!')>>>sys.stderr.write(''.join(sys.stdout.data))foohello world!

How do I access a module written in Python from C?

You can get a pointer to the module object as follows:

module=PyImport_ImportModule("<modulename>");

If the module hasn’t been imported yet (i.e. it is not yet present insys.modules), this initializes the module; otherwise it simply returnsthe value ofsys.modules["<modulename>"]. Note that it doesn’t enter themodule into any namespace – it only ensures it has been initialized and isstored insys.modules.

You can then access the module’s attributes (i.e. any name defined in themodule) as follows:

attr=PyObject_GetAttrString(module,"<attrname>");

CallingPyObject_SetAttrString() to assign to variables in the modulealso works.

How do I interface to C++ objects from Python?

Depending on your requirements, there are many approaches. To do this manually,begin by readingthe “Extending and Embedding” document. Realize that for the Python run-time system, there isn’t awhole lot of difference between C and C++ – so the strategy of building a newPython type around a C structure (pointer) type will also work for C++ objects.

For C++ libraries, seeWriting C is hard; are there any alternatives?.

I added a module using the Setup file and the make fails; why?

Setup must end in a newline, if there is no newline there, the build processfails. (Fixing this requires some ugly shell script hackery, and this bug is sominor that it doesn’t seem worth the effort.)

How do I debug an extension?

When using GDB with dynamically loaded extensions, you can’t set a breakpoint inyour extension until your extension is loaded.

In your.gdbinit file (or interactively), add the command:

br _PyImport_LoadDynamicModule

Then, when you run GDB:

$gdb/local/bin/pythongdb) run myscript.pygdb) continue # repeat until your extension is loadedgdb) finish   # so that your extension is loadedgdb) br myfunction.c:50gdb) continue

I want to compile a Python module on my Linux system, but some files are missing. Why?

Most packaged versions of Python omit some filesrequired for compiling Python extensions.

For Red Hat, install the python3-devel RPM to get the necessary files.

For Debian, runapt-getinstallpython3-dev.

How do I tell “incomplete input” from “invalid input”?

Sometimes you want to emulate the Python interactive interpreter’s behavior,where it gives you a continuation prompt when the input is incomplete (e.g. youtyped the start of an “if” statement or you didn’t close your parentheses ortriple string quotes), but it gives you a syntax error message immediately whenthe input is invalid.

In Python you can use thecodeop module, which approximates the parser’sbehavior sufficiently. IDLE uses this, for example.

The easiest way to do it in C is to callPyRun_InteractiveLoop() (perhapsin a separate thread) and let the Python interpreter handle the input foryou. You can also set thePyOS_ReadlineFunctionPointer() to point at yourcustom input function. SeeModules/readline.c andParser/myreadline.cfor more hints.

How do I find undefined g++ symbols __builtin_new or __pure_virtual?

To dynamically load g++ extension modules, you must recompile Python, relink itusing g++ (change LINKCC in the Python Modules Makefile), and link yourextension module using g++ (e.g.,g++-shared-omymodule.somymodule.o).

Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?

Yes, you can inherit from built-in classes such asint,list,dict, etc.

The Boost Python Library (BPL,https://www.boost.org/libs/python/doc/index.html)provides a way of doing this from C++ (i.e. you can inherit from an extensionclass written in C++ using the BPL).