Skip to content

Latest commit

 

History

History
85 lines (64 loc) · 3.5 KB

capsulethunk.rst

File metadata and controls

85 lines (64 loc) · 3.5 KB

c

PyCapsule API for Python 2.6

The capsulethunk.h header implements the PyCapsule API (with some limitations) in terms of PYCObject. It is only necessary for compatibility with Python 2.6 (or 3.0).

Note

The capsulethunk.h header and this documentation was written by Larry Hastings for the Python documentation.1 It is now maintained as part of the py3c project.2

single: capsulethunk

CObject replaced with Capsule

The :cCapsule <py3:PyCapsule> object was introduced in Python 3.1 and 2.7 to replace :cCObject <py2:PyCObject>. CObjects were useful, but the :cCObject <py2:PyCObject> API was problematic: it didn't permit distinguishing between valid CObjects, which allowed mismatched CObjects to crash the interpreter, and some of its APIs relied on undefined behavior in C. (For further reading on the rationale behind Capsules, please see CPython issue 5630.)

If you're currently using CObjects, and you want to migrate to Python 3, you'll need to switch to Capsules. See the PyCObject section <pycapsule-porting> in the porting guide for instructions.

:cCObject <py2:PyCObject> was deprecated in 3.1 and 2.7 and completely removed in Python 3.2. So, if you need to support versions of Python earlier than 2.7, or Python 3.0, you'll have to support both CObjects and Capsules.

The following example header file capsulethunk.h may solve the problem for you. Simply write your code against the :cCapsule <py3:PyCapsule> API and include this header file after Python.h. Your code will automatically use Capsules in versions of Python with Capsules, and switch to CObjects when Capsules are unavailable.

If you're using py3c, you will need to explicitly #include <py3c/capsulethunk.h>. The file is not included from py3c.h.

Since :cCObject <py2:PyCObject> provides no place to store the capsule's "name", the simulated :cCapsule <py3:PyCapsule> objects created by capsulethunk.h behave slightly differently from real Capsules. Specifically:

  • The name parameter passed in to :cPyCapsule_New is ignored.
  • The name parameter passed in to :cPyCapsule_IsValid and :cPyCapsule_GetPointer is ignored, and no error checking of the name is performed.
  • :cPyCapsule_GetName always returns NULL.
  • :cPyCapsule_SetName always raises an exception and returns failure. (Since there's no way to store a name in a CObject, noisy failure of :cPyCapsule_SetName was deemed preferable to silent failure here.) If this is inconvenient, feel free to modify your local copy as you see fit.

You can find capsulethunk.h at include/py3c/capsulethunk.h. We also include it here for your convenience:

../../include/py3c/capsulethunk.h


Footnotes


  1. CPython issue 13053: Add Capsule migration documentation to "cporting"

  2. CPython issue 24937: Multiple problems in getters & setters in capsulethunk.h