We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

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 and PyTuple_GetItem returns a given item. Lists have similar functions, PyList_Size 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.

CATEGORY: extending

CATEGORY: cpython