Contents
Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C. This is explained in the document Extending and Embedding the Python Interpreter.
Most intermediate or advanced Python books will also cover this topic.
Yes, using the C compatibility features found in C++. Place extern "C" { ... }
around the Python include files and put extern "C"
before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.
There are a number of alternatives to writing your own C extensions, depending on what you’re trying to do.
If you need more speed, Psyco generates x86 assembly code from Python bytecode. You can use Psyco to compile the most time-critical functions in your code, and gain a significant improvement with very little effort, as long as you’re running on a machine with an x86-compatible processor.
Cython and its relative Pyrex are compilers that accept a slightly modified form of Python and generate the corresponding C code. Pyrex makes it possible to write an extension without having to learn Python’s C API.
If you need to interface to some C or C++ library for which no Python extension currently exists, you can try wrapping the library’s data types and functions with a tool such as SWIG. SIP, CXX Boost, or Weave are also alternatives for wrapping C++ libraries.
The highest-level function to do this is PyRun_SimpleString()
which takes a single string argument to be executed in the context of the module __main__
and returns 0 for success and -1 when an exception occurred (including SyntaxError
). If you want more control, usePyRun_String()
; see the source for PyRun_SimpleString()
in Python/pythonrun.c
.
Call the function PyRun_String()
from the previous question with the start symbol Py_eval_input
; it parses an expression, evaluates it and returns its value.
That depends on the object’s type. If it’s a tuple, PyTuple_Size()
returns its length and PyTuple_GetItem()
returns the item at a specified index. Lists have similar functions, PyListSize()
and PyList_GetItem()
.
For strings, PyString_Size()
returns its length and PyString_AsString()
a pointer to its value. Note that Python strings may contain null bytes so C’s strlen()
should not be used.
To test the type of an object, first make sure it isn’t NULL, and then use PyString_Check()
, PyTuple_Check()
, PyList_Check()
, etc.
There is also a high-level API to Python objects which is provided by the so-called ‘abstract’ interface – read Include/abstract.h
for further details. It allows interfacing with any kind of Python sequence using calls like PySequence_Length()
, PySequence_GetItem()
, etc.) as well as many other useful protocols.
You can’t. Use t = PyTuple_New(n)
instead, and fill it with objects using PyTuple_SetItem(t, i, o)
– note that this “eats” a reference count of o
, so you have to Py_INCREF()
it. Lists have similar functions PyList_New(n)
and PyList_SetItem(l, i, o)
. Note that you must set all the tuple items to some value before you pass the tuple to Python code – PyTuple_New(n)
initializes them to NULL, which isn’t a valid Python value.
The PyObject_CallMethod()
function can be used to call an arbitrary method of an object. The parameters are the object, the name of the method to call, a format string like that used with Py_BuildValue()
, and the argument values:
This works for any object that has methods – whether built-in or user-defined. You are responsible for eventually Py_DECREF()
‘ing the return value.
To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming the file object pointer is “f”):
Note that since PyObject_CallObject()
always wants a tuple for the argument 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)”.
In Python code, define an object that supports the write()
method. Assign this object to sys.stdout
and sys.stderr
. Call print_error, or just allow the standard traceback mechanism to work. Then, the output will go wherever your write()
method sends it.
The easiest way to do this is to use the StringIO class in the standard library.
Sample code and use for catching stdout:
You can get a pointer to the module object as follows:
If the module hasn’t been imported yet (i.e. it is not yet present in sys.modules
), this initializes the module; otherwise it simply returns the value of sys.modules["<modulename>"]
. Note that it doesn’t enter the module into any namespace – it only ensures it has been initialized and is stored in sys.modules
.
You can then access the module’s attributes (i.e. any name defined in the module) as follows:
Calling PyObject_SetAttrString()
to assign to variables in the module also works.
Depending on your requirements, there are many approaches. To do this manually, begin by reading the “Extending and Embedding” document. Realize that for the Python run-time system, there isn’t a whole lot of difference between C and C++ – so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.
For C++ libraries, see Writing C is hard; are there any alternatives?.
Setup must end in a newline, if there is no newline there, the build process fails. (Fixing this requires some ugly shell script hackery, and this bug is so minor that it doesn’t seem worth the effort.)
When using GDB with dynamically loaded extensions, you can’t set a breakpoint in your extension until your extension is loaded.
In your .gdbinit
file (or interactively), add the command:
Then, when you run GDB:
Most packaged versions of Python don’t include the /usr/lib/python2.x/config/
directory, which contains various files required for compiling Python extensions.
For Red Hat, install the python-devel RPM to get the necessary files.
For Debian, run apt-get install python-dev
.
This means that you have created an extension module named “yourmodule”, but your module init function does not initialize with that name.
Every module init function will have a line similar to:
If the string passed to this function is not the same name as your extension module, the SystemError
exception will be raised.
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. you typed the start of an “if” statement or you didn’t close your parentheses or triple string quotes), but it gives you a syntax error message immediately when the input is invalid.
In Python you can use the codeop
module, which approximates the parser’s behavior sufficiently. IDLE uses this, for example.
The easiest way to do it in C is to call PyRun_InteractiveLoop()
(perhaps in a separate thread) and let the Python interpreter handle the input for you. You can also set the PyOS_ReadlineFunctionPointer()
to point at your custom input function. See Modules/readline.c
andParser/myreadline.c
for more hints.
However sometimes you have to run the embedded Python interpreter in the same thread as your rest application and you can’t allow thePyRun_InteractiveLoop()
to stop while waiting for user input. The one solution then is to call PyParser_ParseString()
and test for e.error
equal to E_EOF
, which means the input is incomplete). Here’s a sample code fragment, untested, inspired by code from Alex Farber:
Another solution is trying to compile the received string with Py_CompileString()
. If it compiles without errors, try to execute the returned code object by calling PyEval_EvalCode()
. Otherwise save the input for later. If the compilation fails, find out if it’s an error or just more input is required - by extracting the message string from the exception tuple and comparing it to the string “unexpected EOF while parsing”. Here is a complete example using the GNU readline library (you may want to ignore SIGINT while calling readline()):
To dynamically load g++ extension modules, you must recompile Python, relink it using g++ (change LINKCC in the Python Modules Makefile), and link your extension module using g++ (e.g., g++ -shared -o mymodule.so mymodule.o
).
Yes, you can inherit from built-in classes such as int
, list
, dict
, etc.
The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html) provides a way of doing this from C++ (i.e. you can inherit from an extension class written in C++ using the BPL).
You are using a version of Python that uses a 4-byte representation for Unicode characters, but some C extension module you are importing was compiled using a Python that uses a 2-byte representation for Unicode characters (the default).
If instead the name of the undefined symbol starts with PyUnicodeUCS4
, the problem is the reverse: Python was built using 2-byte Unicode characters, and the extension module was compiled using a Python with 4-byte Unicode characters.
This can easily occur when using pre-built extension packages. RedHat Linux 7.x, in particular, provided a “python2” binary that is compiled with 4-byte Unicode. This only causes the link failure if the extension uses any of the PyUnicode_*()
functions. It is also a problem if an extension uses any of the Unicode-related format specifiers for Py_BuildValue()
(or similar) or parameter specifications forPyArg_ParseTuple()
.
You can check the size of the Unicode character a Python interpreter is using by checking the value of sys.maxunicode:
The only way to solve this problem is to use extension modules compiled with a Python binary built using the same size for Unicode characters.
from: https://docs.python.org/2/faq/extending.html