gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1566 line
162KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="1. Extending Python with C or C++" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/extending/extending.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>1. Extending Python with C or C++ &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="2. Defining Extension Types: Tutorial" href="newtypes_tutorial.html" />
  33. <link rel="prev" title="Extending and Embedding the Python Interpreter" href="index.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/extending/extending.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">1. Extending Python with C or C++</a><ul>
  86. <li><a class="reference internal" href="#a-simple-example">1.1. A Simple Example</a></li>
  87. <li><a class="reference internal" href="#intermezzo-errors-and-exceptions">1.2. Intermezzo: Errors and Exceptions</a></li>
  88. <li><a class="reference internal" href="#back-to-the-example">1.3. Back to the Example</a></li>
  89. <li><a class="reference internal" href="#the-module-s-method-table-and-initialization-function">1.4. The Module’s Method Table and Initialization Function</a></li>
  90. <li><a class="reference internal" href="#compilation-and-linkage">1.5. Compilation and Linkage</a></li>
  91. <li><a class="reference internal" href="#calling-python-functions-from-c">1.6. Calling Python Functions from C</a></li>
  92. <li><a class="reference internal" href="#extracting-parameters-in-extension-functions">1.7. Extracting Parameters in Extension Functions</a></li>
  93. <li><a class="reference internal" href="#keyword-parameters-for-extension-functions">1.8. Keyword Parameters for Extension Functions</a></li>
  94. <li><a class="reference internal" href="#building-arbitrary-values">1.9. Building Arbitrary Values</a></li>
  95. <li><a class="reference internal" href="#reference-counts">1.10. Reference Counts</a><ul>
  96. <li><a class="reference internal" href="#reference-counting-in-python">1.10.1. Reference Counting in Python</a></li>
  97. <li><a class="reference internal" href="#ownership-rules">1.10.2. Ownership Rules</a></li>
  98. <li><a class="reference internal" href="#thin-ice">1.10.3. Thin Ice</a></li>
  99. <li><a class="reference internal" href="#null-pointers">1.10.4. NULL Pointers</a></li>
  100. </ul>
  101. </li>
  102. <li><a class="reference internal" href="#writing-extensions-in-c">1.11. Writing Extensions in C++</a></li>
  103. <li><a class="reference internal" href="#providing-a-c-api-for-an-extension-module">1.12. Providing a C API for an Extension Module</a></li>
  104. </ul>
  105. </li>
  106. </ul>
  107. </div>
  108. <div>
  109. <h4>Previous topic</h4>
  110. <p class="topless"><a href="index.html"
  111. title="previous chapter">Extending and Embedding the Python Interpreter</a></p>
  112. </div>
  113. <div>
  114. <h4>Next topic</h4>
  115. <p class="topless"><a href="newtypes_tutorial.html"
  116. title="next chapter"><span class="section-number">2. </span>Defining Extension Types: Tutorial</a></p>
  117. </div>
  118. <div role="note" aria-label="source link">
  119. <h3>This Page</h3>
  120. <ul class="this-page-menu">
  121. <li><a href="../bugs.html">Report a Bug</a></li>
  122. <li>
  123. <a href="https://github.com/python/cpython/blob/main/Doc/extending/extending.rst"
  124. rel="nofollow">Show Source
  125. </a>
  126. </li>
  127. </ul>
  128. </div>
  129. </nav>
  130. </div>
  131. </div>
  132. <div class="related" role="navigation" aria-label="related navigation">
  133. <h3>Navigation</h3>
  134. <ul>
  135. <li class="right" style="margin-right: 10px">
  136. <a href="../genindex.html" title="General Index"
  137. accesskey="I">index</a></li>
  138. <li class="right" >
  139. <a href="../py-modindex.html" title="Python Module Index"
  140. >modules</a> |</li>
  141. <li class="right" >
  142. <a href="newtypes_tutorial.html" title="2. Defining Extension Types: Tutorial"
  143. accesskey="N">next</a> |</li>
  144. <li class="right" >
  145. <a href="index.html" title="Extending and Embedding the Python Interpreter"
  146. accesskey="P">previous</a> |</li>
  147. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  148. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  149. <li class="switchers">
  150. <div class="language_switcher_placeholder"></div>
  151. <div class="version_switcher_placeholder"></div>
  152. </li>
  153. <li>
  154. </li>
  155. <li id="cpython-language-and-version">
  156. <a href="../index.html">3.12.3 Documentation</a> &#187;
  157. </li>
  158. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li>
  159. <li class="nav-item nav-item-this"><a href=""><span class="section-number">1. </span>Extending Python with C or C++</a></li>
  160. <li class="right">
  161. <div class="inline-search" role="search">
  162. <form class="inline-search" action="../search.html" method="get">
  163. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  164. <input type="submit" value="Go" />
  165. </form>
  166. </div>
  167. |
  168. </li>
  169. <li class="right">
  170. <label class="theme-selector-label">
  171. Theme
  172. <select class="theme-selector" oninput="activateTheme(this.value)">
  173. <option value="auto" selected>Auto</option>
  174. <option value="light">Light</option>
  175. <option value="dark">Dark</option>
  176. </select>
  177. </label> |</li>
  178. </ul>
  179. </div>
  180. <div class="document">
  181. <div class="documentwrapper">
  182. <div class="bodywrapper">
  183. <div class="body" role="main">
  184. <section id="extending-python-with-c-or-c">
  185. <span id="extending-intro"></span><h1><span class="section-number">1. </span>Extending Python with C or C++<a class="headerlink" href="#extending-python-with-c-or-c" title="Link to this heading">¶</a></h1>
  186. <p>It is quite easy to add new built-in modules to Python, if you know how to
  187. program in C. Such <em class="dfn">extension modules</em> can do two things that can’t be
  188. done directly in Python: they can implement new built-in object types, and they
  189. can call C library functions and system calls.</p>
  190. <p>To support extensions, the Python API (Application Programmers Interface)
  191. defines a set of functions, macros and variables that provide access to most
  192. aspects of the Python run-time system. The Python API is incorporated in a C
  193. source file by including the header <code class="docutils literal notranslate"><span class="pre">&quot;Python.h&quot;</span></code>.</p>
  194. <p>The compilation of an extension module depends on its intended use as well as on
  195. your system setup; details are given in later chapters.</p>
  196. <div class="admonition note">
  197. <p class="admonition-title">Note</p>
  198. <p>The C extension interface is specific to CPython, and extension modules do
  199. not work on other Python implementations. In many cases, it is possible to
  200. avoid writing C extensions and preserve portability to other implementations.
  201. For example, if your use case is calling C library functions or system calls,
  202. you should consider using the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module or the <a class="reference external" href="https://cffi.readthedocs.io/">cffi</a> library rather than writing
  203. custom C code.
  204. These modules let you write Python code to interface with C code and are more
  205. portable between implementations of Python than writing and compiling a C
  206. extension module.</p>
  207. </div>
  208. <section id="a-simple-example">
  209. <span id="extending-simpleexample"></span><h2><span class="section-number">1.1. </span>A Simple Example<a class="headerlink" href="#a-simple-example" title="Link to this heading">¶</a></h2>
  210. <p>Let’s create an extension module called <code class="docutils literal notranslate"><span class="pre">spam</span></code> (the favorite food of Monty
  211. Python fans…) and let’s say we want to create a Python interface to the C
  212. library function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> <a class="footnote-reference brackets" href="#id5" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>. This function takes a null-terminated
  213. character string as argument and returns an integer. We want this function to
  214. be callable from Python as follows:</p>
  215. <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">spam</span>
  216. <span class="gp">&gt;&gt;&gt; </span><span class="n">status</span> <span class="o">=</span> <span class="n">spam</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s2">&quot;ls -l&quot;</span><span class="p">)</span>
  217. </pre></div>
  218. </div>
  219. <p>Begin by creating a file <code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>. (Historically, if a module is
  220. called <code class="docutils literal notranslate"><span class="pre">spam</span></code>, the C file containing its implementation is called
  221. <code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>; if the module name is very long, like <code class="docutils literal notranslate"><span class="pre">spammify</span></code>, the
  222. module name can be just <code class="file docutils literal notranslate"><span class="pre">spammify.c</span></code>.)</p>
  223. <p>The first two lines of our file can be:</p>
  224. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define PY_SSIZE_T_CLEAN</span>
  225. <span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;Python.h&gt;</span>
  226. </pre></div>
  227. </div>
  228. <p>which pulls in the Python API (you can add a comment describing the purpose of
  229. the module and a copyright notice if you like).</p>
  230. <div class="admonition note">
  231. <p class="admonition-title">Note</p>
  232. <p>Since Python may define some pre-processor definitions which affect the standard
  233. headers on some systems, you <em>must</em> include <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> before any standard
  234. headers are included.</p>
  235. <p>It is recommended to always define <code class="docutils literal notranslate"><span class="pre">PY_SSIZE_T_CLEAN</span></code> before including
  236. <code class="docutils literal notranslate"><span class="pre">Python.h</span></code>. See <a class="reference internal" href="#parsetuple"><span class="std std-ref">Extracting Parameters in Extension Functions</span></a> for a description of this macro.</p>
  237. </div>
  238. <p>All user-visible symbols defined by <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> have a prefix of <code class="docutils literal notranslate"><span class="pre">Py</span></code> or
  239. <code class="docutils literal notranslate"><span class="pre">PY</span></code>, except those defined in standard header files. For convenience, and
  240. since they are used extensively by the Python interpreter, <code class="docutils literal notranslate"><span class="pre">&quot;Python.h&quot;</span></code>
  241. includes a few standard header files: <code class="docutils literal notranslate"><span class="pre">&lt;stdio.h&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;string.h&gt;</span></code>,
  242. <code class="docutils literal notranslate"><span class="pre">&lt;errno.h&gt;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&lt;stdlib.h&gt;</span></code>. If the latter header file does not exist on
  243. your system, it declares the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> and
  244. <code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code> directly.</p>
  245. <p>The next thing we add to our module file is the C function that will be called
  246. when the Python expression <code class="docutils literal notranslate"><span class="pre">spam.system(string)</span></code> is evaluated (we’ll see
  247. shortly how it ends up being called):</p>
  248. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  249. <span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  250. <span class="p">{</span>
  251. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">command</span><span class="p">;</span>
  252. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">sts</span><span class="p">;</span>
  253. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
  254. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  255. <span class="w"> </span><span class="n">sts</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
  256. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
  257. <span class="p">}</span>
  258. </pre></div>
  259. </div>
  260. <p>There is a straightforward translation from the argument list in Python (for
  261. example, the single expression <code class="docutils literal notranslate"><span class="pre">&quot;ls</span> <span class="pre">-l&quot;</span></code>) to the arguments passed to the C
  262. function. The C function always has two arguments, conventionally named <em>self</em>
  263. and <em>args</em>.</p>
  264. <p>The <em>self</em> argument points to the module object for module-level functions;
  265. for a method it would point to the object instance.</p>
  266. <p>The <em>args</em> argument will be a pointer to a Python tuple object containing the
  267. arguments. Each item of the tuple corresponds to an argument in the call’s
  268. argument list. The arguments are Python objects — in order to do anything
  269. with them in our C function we have to convert them to C values. The function
  270. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> in the Python API checks the argument types and
  271. converts them to C values. It uses a template string to determine the required
  272. types of the arguments as well as the types of the C variables into which to
  273. store the converted values. More about this later.</p>
  274. <p><a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> returns true (nonzero) if all arguments have the right
  275. type and its components have been stored in the variables whose addresses are
  276. passed. It returns false (zero) if an invalid argument list was passed. In the
  277. latter case it also raises an appropriate exception so the calling function can
  278. return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> immediately (as we saw in the example).</p>
  279. </section>
  280. <section id="intermezzo-errors-and-exceptions">
  281. <span id="extending-errors"></span><h2><span class="section-number">1.2. </span>Intermezzo: Errors and Exceptions<a class="headerlink" href="#intermezzo-errors-and-exceptions" title="Link to this heading">¶</a></h2>
  282. <p>An important convention throughout the Python interpreter is the following: when
  283. a function fails, it should set an exception condition and return an error value
  284. (usually <code class="docutils literal notranslate"><span class="pre">-1</span></code> or a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointer). Exception information is stored in
  285. three members of the interpreter’s thread state. These are <code class="docutils literal notranslate"><span class="pre">NULL</span></code> if
  286. there is no exception. Otherwise they are the C equivalents of the members
  287. of the Python tuple returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>. These are the
  288. exception type, exception instance, and a traceback object. It is important
  289. to know about them to understand how errors are passed around.</p>
  290. <p>The Python API defines a number of functions to set various types of exceptions.</p>
  291. <p>The most common one is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a>. Its arguments are an exception
  292. object and a C string. The exception object is usually a predefined object like
  293. <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>. The C string indicates the cause of the error
  294. and is converted to a Python string object and stored as the “associated value”
  295. of the exception.</p>
  296. <p>Another useful function is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetFromErrno" title="PyErr_SetFromErrno"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromErrno()</span></code></a>, which only takes an
  297. exception argument and constructs the associated value by inspection of the
  298. global variable <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code>. The most general function is
  299. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetObject" title="PyErr_SetObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetObject()</span></code></a>, which takes two object arguments, the exception and
  300. its associated value. You don’t need to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> the objects passed
  301. to any of these functions.</p>
  302. <p>You can test non-destructively whether an exception has been set with
  303. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>. This returns the current exception object, or <code class="docutils literal notranslate"><span class="pre">NULL</span></code>
  304. if no exception has occurred. You normally don’t need to call
  305. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to see whether an error occurred in a function call,
  306. since you should be able to tell from the return value.</p>
  307. <p>When a function <em>f</em> that calls another function <em>g</em> detects that the latter
  308. fails, <em>f</em> should itself return an error value (usually <code class="docutils literal notranslate"><span class="pre">NULL</span></code> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>). It
  309. should <em>not</em> call one of the <code class="docutils literal notranslate"><span class="pre">PyErr_*</span></code> functions — one has already
  310. been called by <em>g</em>. <em>f</em>’s caller is then supposed to also return an error
  311. indication to <em>its</em> caller, again <em>without</em> calling <code class="docutils literal notranslate"><span class="pre">PyErr_*</span></code>, and so on
  312. — the most detailed cause of the error was already reported by the function
  313. that first detected it. Once the error reaches the Python interpreter’s main
  314. loop, this aborts the currently executing Python code and tries to find an
  315. exception handler specified by the Python programmer.</p>
  316. <p>(There are situations where a module can actually give a more detailed error
  317. message by calling another <code class="docutils literal notranslate"><span class="pre">PyErr_*</span></code> function, and in such cases it is
  318. fine to do so. As a general rule, however, this is not necessary, and can cause
  319. information about the cause of the error to be lost: most operations can fail
  320. for a variety of reasons.)</p>
  321. <p>To ignore an exception set by a function call that failed, the exception
  322. condition must be cleared explicitly by calling <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>. The only
  323. time C code should call <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> is if it doesn’t want to pass the
  324. error on to the interpreter but wants to handle it completely by itself
  325. (possibly by trying something else, or pretending nothing went wrong).</p>
  326. <p>Every failing <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call must be turned into an exception — the
  327. direct caller of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> (or <code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code>) must call
  328. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NoMemory" title="PyErr_NoMemory"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NoMemory()</span></code></a> and return a failure indicator itself. All the
  329. object-creating functions (for example, <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a>) already do
  330. this, so this note is only relevant to those who call <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> directly.</p>
  331. <p>Also note that, with the important exception of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> and
  332. friends, functions that return an integer status usually return a positive value
  333. or zero for success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> for failure, like Unix system calls.</p>
  334. <p>Finally, be careful to clean up garbage (by making <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> or
  335. <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> calls for objects you have already created) when you return
  336. an error indicator!</p>
  337. <p>The choice of which exception to raise is entirely yours. There are predeclared
  338. C objects corresponding to all built-in Python exceptions, such as
  339. <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>, which you can use directly. Of course, you
  340. should choose exceptions wisely — don’t use <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code> to mean
  341. that a file couldn’t be opened (that should probably be <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_OSError</span></code>).
  342. If something’s wrong with the argument list, the <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>
  343. function usually raises <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code>. If you have an argument whose
  344. value must be in a particular range or must satisfy other conditions,
  345. <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ValueError</span></code> is appropriate.</p>
  346. <p>You can also define a new exception that is unique to your module. For this, you
  347. usually declare a static object variable at the beginning of your file:</p>
  348. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">SpamError</span><span class="p">;</span>
  349. </pre></div>
  350. </div>
  351. <p>and initialize it in your module’s initialization function (<code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code>)
  352. with an exception object:</p>
  353. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
  354. <span class="nf">PyInit_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  355. <span class="p">{</span>
  356. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">m</span><span class="p">;</span>
  357. <span class="w"> </span><span class="n">m</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">spammodule</span><span class="p">);</span>
  358. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">m</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  359. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  360. <span class="w"> </span><span class="n">SpamError</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyErr_NewException</span><span class="p">(</span><span class="s">&quot;spam.error&quot;</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">);</span>
  361. <span class="w"> </span><span class="n">Py_XINCREF</span><span class="p">(</span><span class="n">SpamError</span><span class="p">);</span>
  362. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;error&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">SpamError</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  363. <span class="w"> </span><span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">SpamError</span><span class="p">);</span>
  364. <span class="w"> </span><span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">SpamError</span><span class="p">);</span>
  365. <span class="w"> </span><span class="n">Py_DECREF</span><span class="p">(</span><span class="n">m</span><span class="p">);</span>
  366. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  367. <span class="w"> </span><span class="p">}</span>
  368. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">m</span><span class="p">;</span>
  369. <span class="p">}</span>
  370. </pre></div>
  371. </div>
  372. <p>Note that the Python name for the exception object is <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code>. The
  373. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NewException" title="PyErr_NewException"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewException()</span></code></a> function may create a class with the base class
  374. being <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> (unless another class is passed in instead of <code class="docutils literal notranslate"><span class="pre">NULL</span></code>),
  375. described in <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a>.</p>
  376. <p>Note also that the <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> variable retains a reference to the newly
  377. created exception class; this is intentional! Since the exception could be
  378. removed from the module by external code, an owned reference to the class is
  379. needed to ensure that it will not be discarded, causing <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> to
  380. become a dangling pointer. Should it become a dangling pointer, C code which
  381. raises the exception could cause a core dump or other unintended side effects.</p>
  382. <p>We discuss the use of <a class="reference internal" href="../c-api/intro.html#c.PyMODINIT_FUNC" title="PyMODINIT_FUNC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code></a> as a function return type later in this
  383. sample.</p>
  384. <p>The <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code> exception can be raised in your extension module using a
  385. call to <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> as shown below:</p>
  386. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  387. <span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  388. <span class="p">{</span>
  389. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">command</span><span class="p">;</span>
  390. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">sts</span><span class="p">;</span>
  391. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
  392. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  393. <span class="w"> </span><span class="n">sts</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
  394. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">sts</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  395. <span class="w"> </span><span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">SpamError</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;System command failed&quot;</span><span class="p">);</span>
  396. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  397. <span class="w"> </span><span class="p">}</span>
  398. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
  399. <span class="p">}</span>
  400. </pre></div>
  401. </div>
  402. </section>
  403. <section id="back-to-the-example">
  404. <span id="backtoexample"></span><h2><span class="section-number">1.3. </span>Back to the Example<a class="headerlink" href="#back-to-the-example" title="Link to this heading">¶</a></h2>
  405. <p>Going back to our example function, you should now be able to understand this
  406. statement:</p>
  407. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
  408. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  409. </pre></div>
  410. </div>
  411. <p>It returns <code class="docutils literal notranslate"><span class="pre">NULL</span></code> (the error indicator for functions returning object pointers)
  412. if an error is detected in the argument list, relying on the exception set by
  413. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>. Otherwise the string value of the argument has been
  414. copied to the local variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code>. This is a pointer assignment and
  415. you are not supposed to modify the string to which it points (so in Standard C,
  416. the variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code> should properly be declared as <code class="docutils literal notranslate"><span class="pre">const</span> <span class="pre">char</span>
  417. <span class="pre">*command</span></code>).</p>
  418. <p>The next statement is a call to the Unix function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code>, passing it
  419. the string we just got from <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>:</p>
  420. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">sts</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
  421. </pre></div>
  422. </div>
  423. <p>Our <code class="xref py py-func docutils literal notranslate"><span class="pre">spam.system()</span></code> function must return the value of <code class="xref c c-data docutils literal notranslate"><span class="pre">sts</span></code> as a
  424. Python object. This is done using the function <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a>.</p>
  425. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">return</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
  426. </pre></div>
  427. </div>
  428. <p>In this case, it will return an integer object. (Yes, even integers are objects
  429. on the heap in Python!)</p>
  430. <p>If you have a C function that returns no useful argument (a function returning
  431. <span class="c-expr sig sig-inline c"><span class="kt">void</span></span>), the corresponding Python function must return <code class="docutils literal notranslate"><span class="pre">None</span></code>. You
  432. need this idiom to do so (which is implemented by the <a class="reference internal" href="../c-api/none.html#c.Py_RETURN_NONE" title="Py_RETURN_NONE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_NONE</span></code></a>
  433. macro):</p>
  434. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
  435. <span class="k">return</span><span class="w"> </span><span class="n">Py_None</span><span class="p">;</span>
  436. </pre></div>
  437. </div>
  438. <p><a class="reference internal" href="../c-api/none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> is the C name for the special Python object <code class="docutils literal notranslate"><span class="pre">None</span></code>. It is a
  439. genuine Python object rather than a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointer, which means “error” in most
  440. contexts, as we have seen.</p>
  441. </section>
  442. <section id="the-module-s-method-table-and-initialization-function">
  443. <span id="methodtable"></span><h2><span class="section-number">1.4. </span>The Module’s Method Table and Initialization Function<a class="headerlink" href="#the-module-s-method-table-and-initialization-function" title="Link to this heading">¶</a></h2>
  444. <p>I promised to show how <code class="xref c c-func docutils literal notranslate"><span class="pre">spam_system()</span></code> is called from Python programs.
  445. First, we need to list its name and address in a “method table”:</p>
  446. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyMethodDef</span><span class="w"> </span><span class="n">SpamMethods</span><span class="p">[]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
  447. <span class="w"> </span><span class="p">...</span>
  448. <span class="w"> </span><span class="p">{</span><span class="s">&quot;system&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">spam_system</span><span class="p">,</span><span class="w"> </span><span class="n">METH_VARARGS</span><span class="p">,</span>
  449. <span class="w"> </span><span class="s">&quot;Execute a shell command.&quot;</span><span class="p">},</span>
  450. <span class="w"> </span><span class="p">...</span>
  451. <span class="w"> </span><span class="p">{</span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">}</span><span class="w"> </span><span class="cm">/* Sentinel */</span>
  452. <span class="p">};</span>
  453. </pre></div>
  454. </div>
  455. <p>Note the third entry (<code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>). This is a flag telling the interpreter
  456. the calling convention to be used for the C function. It should normally always
  457. be <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code> or <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span> <span class="pre">|</span> <span class="pre">METH_KEYWORDS</span></code>; a value of <code class="docutils literal notranslate"><span class="pre">0</span></code> means
  458. that an obsolete variant of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> is used.</p>
  459. <p>When using only <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>, the function should expect the Python-level
  460. parameters to be passed in as a tuple acceptable for parsing via
  461. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>; more information on this function is provided below.</p>
  462. <p>The <a class="reference internal" href="../c-api/structures.html#c.METH_KEYWORDS" title="METH_KEYWORDS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_KEYWORDS</span></code></a> bit may be set in the third field if keyword
  463. arguments should be passed to the function. In this case, the C function should
  464. accept a third <code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code> parameter which will be a dictionary of keywords.
  465. Use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> to parse the arguments to such a
  466. function.</p>
  467. <p>The method table must be referenced in the module definition structure:</p>
  468. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="k">struct</span><span class="w"> </span><span class="nc">PyModuleDef</span><span class="w"> </span><span class="n">spammodule</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
  469. <span class="w"> </span><span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span>
  470. <span class="w"> </span><span class="s">&quot;spam&quot;</span><span class="p">,</span><span class="w"> </span><span class="cm">/* name of module */</span>
  471. <span class="w"> </span><span class="n">spam_doc</span><span class="p">,</span><span class="w"> </span><span class="cm">/* module documentation, may be NULL */</span>
  472. <span class="w"> </span><span class="mi">-1</span><span class="p">,</span><span class="w"> </span><span class="cm">/* size of per-interpreter state of the module,</span>
  473. <span class="cm"> or -1 if the module keeps state in global variables. */</span>
  474. <span class="w"> </span><span class="n">SpamMethods</span>
  475. <span class="p">};</span>
  476. </pre></div>
  477. </div>
  478. <p>This structure, in turn, must be passed to the interpreter in the module’s
  479. initialization function. The initialization function must be named
  480. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_name()</span></code>, where <em>name</em> is the name of the module, and should be the
  481. only non-<code class="docutils literal notranslate"><span class="pre">static</span></code> item defined in the module file:</p>
  482. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
  483. <span class="nf">PyInit_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  484. <span class="p">{</span>
  485. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">spammodule</span><span class="p">);</span>
  486. <span class="p">}</span>
  487. </pre></div>
  488. </div>
  489. <p>Note that <a class="reference internal" href="../c-api/intro.html#c.PyMODINIT_FUNC" title="PyMODINIT_FUNC"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code></a> declares the function as <code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code> return type,
  490. declares any special linkage declarations required by the platform, and for C++
  491. declares the function as <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>.</p>
  492. <p>When the Python program imports module <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> for the first time,
  493. <code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code> is called. (See below for comments about embedding Python.)
  494. It calls <a class="reference internal" href="../c-api/module.html#c.PyModule_Create" title="PyModule_Create"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_Create()</span></code></a>, which returns a module object, and
  495. inserts built-in function objects into the newly created module based upon the
  496. table (an array of <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structures) found in the module definition.
  497. <a class="reference internal" href="../c-api/module.html#c.PyModule_Create" title="PyModule_Create"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_Create()</span></code></a> returns a pointer to the module object
  498. that it creates. It may abort with a fatal error for
  499. certain errors, or return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> if the module could not be initialized
  500. satisfactorily. The init function must return the module object to its caller,
  501. so that it then gets inserted into <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
  502. <p>When embedding Python, the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code> function is not called
  503. automatically unless there’s an entry in the <code class="xref c c-data docutils literal notranslate"><span class="pre">PyImport_Inittab</span></code> table.
  504. To add the module to the initialization table, use <a class="reference internal" href="../c-api/import.html#c.PyImport_AppendInittab" title="PyImport_AppendInittab"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_AppendInittab()</span></code></a>,
  505. optionally followed by an import of the module:</p>
  506. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
  507. <span class="nf">main</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">argc</span><span class="p">,</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
  508. <span class="p">{</span>
  509. <span class="w"> </span><span class="kt">wchar_t</span><span class="w"> </span><span class="o">*</span><span class="n">program</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Py_DecodeLocale</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span><span class="w"> </span><span class="nb">NULL</span><span class="p">);</span>
  510. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">program</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  511. <span class="w"> </span><span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;Fatal error: cannot decode argv[0]</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
  512. <span class="w"> </span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
  513. <span class="w"> </span><span class="p">}</span>
  514. <span class="w"> </span><span class="cm">/* Add a built-in module, before Py_Initialize */</span>
  515. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">PyImport_AppendInittab</span><span class="p">(</span><span class="s">&quot;spam&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">PyInit_spam</span><span class="p">)</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">-1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  516. <span class="w"> </span><span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;Error: could not extend in-built modules table</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
  517. <span class="w"> </span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
  518. <span class="w"> </span><span class="p">}</span>
  519. <span class="w"> </span><span class="cm">/* Pass argv[0] to the Python interpreter */</span>
  520. <span class="w"> </span><span class="n">Py_SetProgramName</span><span class="p">(</span><span class="n">program</span><span class="p">);</span>
  521. <span class="w"> </span><span class="cm">/* Initialize the Python interpreter. Required.</span>
  522. <span class="cm"> If this step fails, it will be a fatal error. */</span>
  523. <span class="w"> </span><span class="n">Py_Initialize</span><span class="p">();</span>
  524. <span class="w"> </span><span class="cm">/* Optionally import the module; alternatively,</span>
  525. <span class="cm"> import can be deferred until the embedded script</span>
  526. <span class="cm"> imports it. */</span>
  527. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">pmodule</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyImport_ImportModule</span><span class="p">(</span><span class="s">&quot;spam&quot;</span><span class="p">);</span>
  528. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">pmodule</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  529. <span class="w"> </span><span class="n">PyErr_Print</span><span class="p">();</span>
  530. <span class="w"> </span><span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;Error: could not import module &#39;spam&#39;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
  531. <span class="w"> </span><span class="p">}</span>
  532. <span class="w"> </span><span class="p">...</span>
  533. <span class="w"> </span><span class="n">PyMem_RawFree</span><span class="p">(</span><span class="n">program</span><span class="p">);</span>
  534. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
  535. <span class="p">}</span>
  536. </pre></div>
  537. </div>
  538. <div class="admonition note">
  539. <p class="admonition-title">Note</p>
  540. <p>Removing entries from <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> or importing compiled modules into
  541. multiple interpreters within a process (or following a <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code> without an
  542. intervening <code class="xref c c-func docutils literal notranslate"><span class="pre">exec()</span></code>) can create problems for some extension modules.
  543. Extension module authors should exercise caution when initializing internal data
  544. structures.</p>
  545. </div>
  546. <p>A more substantial example module is included in the Python source distribution
  547. as <code class="file docutils literal notranslate"><span class="pre">Modules/xxmodule.c</span></code>. This file may be used as a template or simply
  548. read as an example.</p>
  549. <div class="admonition note">
  550. <p class="admonition-title">Note</p>
  551. <p>Unlike our <code class="docutils literal notranslate"><span class="pre">spam</span></code> example, <code class="docutils literal notranslate"><span class="pre">xxmodule</span></code> uses <em>multi-phase initialization</em>
  552. (new in Python 3.5), where a PyModuleDef structure is returned from
  553. <code class="docutils literal notranslate"><span class="pre">PyInit_spam</span></code>, and creation of the module is left to the import machinery.
  554. For details on multi-phase initialization, see <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0489/"><strong>PEP 489</strong></a>.</p>
  555. </div>
  556. </section>
  557. <section id="compilation-and-linkage">
  558. <span id="compilation"></span><h2><span class="section-number">1.5. </span>Compilation and Linkage<a class="headerlink" href="#compilation-and-linkage" title="Link to this heading">¶</a></h2>
  559. <p>There are two more things to do before you can use your new extension: compiling
  560. and linking it with the Python system. If you use dynamic loading, the details
  561. may depend on the style of dynamic loading your system uses; see the chapters
  562. about building extension modules (chapter <a class="reference internal" href="building.html#building"><span class="std std-ref">Building C and C++ Extensions</span></a>) and additional
  563. information that pertains only to building on Windows (chapter
  564. <a class="reference internal" href="windows.html#building-on-windows"><span class="std std-ref">Building C and C++ Extensions on Windows</span></a>) for more information about this.</p>
  565. <p>If you can’t use dynamic loading, or if you want to make your module a permanent
  566. part of the Python interpreter, you will have to change the configuration setup
  567. and rebuild the interpreter. Luckily, this is very simple on Unix: just place
  568. your file (<code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code> for example) in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code> directory
  569. of an unpacked source distribution, add a line to the file
  570. <code class="file docutils literal notranslate"><span class="pre">Modules/Setup.local</span></code> describing your file:</p>
  571. <div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>spam<span class="w"> </span>spammodule.o
  572. </pre></div>
  573. </div>
  574. <p>and rebuild the interpreter by running <strong class="program">make</strong> in the toplevel
  575. directory. You can also run <strong class="program">make</strong> in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code>
  576. subdirectory, but then you must first rebuild <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> there by running
  577. ‘<strong class="program">make</strong> Makefile’. (This is necessary each time you change the
  578. <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file.)</p>
  579. <p>If your module requires additional libraries to link with, these can be listed
  580. on the line in the configuration file as well, for instance:</p>
  581. <div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>spam<span class="w"> </span>spammodule.o<span class="w"> </span>-lX11
  582. </pre></div>
  583. </div>
  584. </section>
  585. <section id="calling-python-functions-from-c">
  586. <span id="callingpython"></span><h2><span class="section-number">1.6. </span>Calling Python Functions from C<a class="headerlink" href="#calling-python-functions-from-c" title="Link to this heading">¶</a></h2>
  587. <p>So far we have concentrated on making C functions callable from Python. The
  588. reverse is also useful: calling Python functions from C. This is especially the
  589. case for libraries that support so-called “callback” functions. If a C
  590. interface makes use of callbacks, the equivalent Python often needs to provide a
  591. callback mechanism to the Python programmer; the implementation will require
  592. calling the Python callback functions from a C callback. Other uses are also
  593. imaginable.</p>
  594. <p>Fortunately, the Python interpreter is easily called recursively, and there is a
  595. standard interface to call a Python function. (I won’t dwell on how to call the
  596. Python parser with a particular string as input — if you’re interested, have a
  597. look at the implementation of the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> command line option in
  598. <code class="file docutils literal notranslate"><span class="pre">Modules/main.c</span></code> from the Python source code.)</p>
  599. <p>Calling a Python function is easy. First, the Python program must somehow pass
  600. you the Python function object. You should provide a function (or some other
  601. interface) to do this. When this function is called, save a pointer to the
  602. Python function object (be careful to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> it!) in a global
  603. variable — or wherever you see fit. For example, the following function might
  604. be part of a module definition:</p>
  605. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">my_callback</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  606. <span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  607. <span class="nf">my_set_callback</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">dummy</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  608. <span class="p">{</span>
  609. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  610. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">temp</span><span class="p">;</span>
  611. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;O:set_callback&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">temp</span><span class="p">))</span><span class="w"> </span><span class="p">{</span>
  612. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">temp</span><span class="p">))</span><span class="w"> </span><span class="p">{</span>
  613. <span class="w"> </span><span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;parameter must be callable&quot;</span><span class="p">);</span>
  614. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  615. <span class="w"> </span><span class="p">}</span>
  616. <span class="w"> </span><span class="n">Py_XINCREF</span><span class="p">(</span><span class="n">temp</span><span class="p">);</span><span class="w"> </span><span class="cm">/* Add a reference to new callback */</span>
  617. <span class="w"> </span><span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">my_callback</span><span class="p">);</span><span class="w"> </span><span class="cm">/* Dispose of previous callback */</span>
  618. <span class="w"> </span><span class="n">my_callback</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">temp</span><span class="p">;</span><span class="w"> </span><span class="cm">/* Remember new callback */</span>
  619. <span class="w"> </span><span class="cm">/* Boilerplate to return &quot;None&quot; */</span>
  620. <span class="w"> </span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
  621. <span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Py_None</span><span class="p">;</span>
  622. <span class="w"> </span><span class="p">}</span>
  623. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">result</span><span class="p">;</span>
  624. <span class="p">}</span>
  625. </pre></div>
  626. </div>
  627. <p>This function must be registered with the interpreter using the
  628. <a class="reference internal" href="../c-api/structures.html#c.METH_VARARGS" title="METH_VARARGS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a> flag; this is described in section <a class="reference internal" href="#methodtable"><span class="std std-ref">The Module’s Method Table and Initialization Function</span></a>. The
  629. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function and its arguments are documented in section
  630. <a class="reference internal" href="#parsetuple"><span class="std std-ref">Extracting Parameters in Extension Functions</span></a>.</p>
  631. <p>The macros <a class="reference internal" href="../c-api/refcounting.html#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> increment/decrement the
  632. reference count of an object and are safe in the presence of <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointers
  633. (but note that <em>temp</em> will not be <code class="docutils literal notranslate"><span class="pre">NULL</span></code> in this context). More info on them
  634. in section <a class="reference internal" href="#refcounts"><span class="std std-ref">Reference Counts</span></a>.</p>
  635. <p id="index-1">Later, when it is time to call the function, you call the C function
  636. <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>. This function has two arguments, both pointers to
  637. arbitrary Python objects: the Python function, and the argument list. The
  638. argument list must always be a tuple object, whose length is the number of
  639. arguments. To call the Python function with no arguments, pass in <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, or
  640. an empty tuple; to call it with one argument, pass a singleton tuple.
  641. <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> returns a tuple when its format string consists of zero
  642. or more format codes between parentheses. For example:</p>
  643. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span><span class="w"> </span><span class="n">arg</span><span class="p">;</span>
  644. <span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
  645. <span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">result</span><span class="p">;</span>
  646. <span class="p">...</span>
  647. <span class="n">arg</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">123</span><span class="p">;</span>
  648. <span class="p">...</span>
  649. <span class="cm">/* Time to call the callback */</span>
  650. <span class="n">arglist</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(i)&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">arg</span><span class="p">);</span>
  651. <span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span><span class="w"> </span><span class="n">arglist</span><span class="p">);</span>
  652. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
  653. </pre></div>
  654. </div>
  655. <p><a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> returns a Python object pointer: this is the return
  656. value of the Python function. <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is
  657. “reference-count-neutral” with respect to its arguments. In the example a new
  658. tuple was created to serve as the argument list, which is
  659. <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>-ed immediately after the <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>
  660. call.</p>
  661. <p>The return value of <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is “new”: either it is a brand
  662. new object, or it is an existing object whose reference count has been
  663. incremented. So, unless you want to save it in a global variable, you should
  664. somehow <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> the result, even (especially!) if you are not
  665. interested in its value.</p>
  666. <p>Before you do this, however, it is important to check that the return value
  667. isn’t <code class="docutils literal notranslate"><span class="pre">NULL</span></code>. If it is, the Python function terminated by raising an exception.
  668. If the C code that called <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is called from Python, it
  669. should now return an error indication to its Python caller, so the interpreter
  670. can print a stack trace, or the calling Python code can handle the exception.
  671. If this is not possible or desirable, the exception should be cleared by calling
  672. <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>. For example:</p>
  673. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">result</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  674. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="cm">/* Pass error back */</span>
  675. <span class="p">...</span><span class="n">use</span><span class="w"> </span><span class="n">result</span><span class="p">...</span>
  676. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
  677. </pre></div>
  678. </div>
  679. <p>Depending on the desired interface to the Python callback function, you may also
  680. have to provide an argument list to <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>. In some cases
  681. the argument list is also provided by the Python program, through the same
  682. interface that specified the callback function. It can then be saved and used
  683. in the same manner as the function object. In other cases, you may have to
  684. construct a new tuple to pass as the argument list. The simplest way to do this
  685. is to call <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>. For example, if you want to pass an integral
  686. event code, you might use the following code:</p>
  687. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
  688. <span class="p">...</span>
  689. <span class="n">arglist</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(l)&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">eventcode</span><span class="p">);</span>
  690. <span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span><span class="w"> </span><span class="n">arglist</span><span class="p">);</span>
  691. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
  692. <span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">result</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  693. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="cm">/* Pass error back */</span>
  694. <span class="cm">/* Here maybe use the result */</span>
  695. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
  696. </pre></div>
  697. </div>
  698. <p>Note the placement of <code class="docutils literal notranslate"><span class="pre">Py_DECREF(arglist)</span></code> immediately after the call, before
  699. the error check! Also note that strictly speaking this code is not complete:
  700. <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> may run out of memory, and this should be checked.</p>
  701. <p>You may also call a function with keyword arguments by using
  702. <a class="reference internal" href="../c-api/call.html#c.PyObject_Call" title="PyObject_Call"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Call()</span></code></a>, which supports arguments and keyword arguments. As in
  703. the above example, we use <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> to construct the dictionary.</p>
  704. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">dict</span><span class="p">;</span>
  705. <span class="p">...</span>
  706. <span class="n">dict</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;{s:i}&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;name&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">val</span><span class="p">);</span>
  707. <span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyObject_Call</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="n">dict</span><span class="p">);</span>
  708. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">dict</span><span class="p">);</span>
  709. <span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">result</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  710. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="cm">/* Pass error back */</span>
  711. <span class="cm">/* Here maybe use the result */</span>
  712. <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
  713. </pre></div>
  714. </div>
  715. </section>
  716. <section id="extracting-parameters-in-extension-functions">
  717. <span id="parsetuple"></span><h2><span class="section-number">1.7. </span>Extracting Parameters in Extension Functions<a class="headerlink" href="#extracting-parameters-in-extension-functions" title="Link to this heading">¶</a></h2>
  718. <p id="index-2">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function is declared as follows:</p>
  719. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span><span class="w"> </span><span class="nf">PyArg_ParseTuple</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">arg</span><span class="p">,</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">format</span><span class="p">,</span><span class="w"> </span><span class="p">...);</span>
  720. </pre></div>
  721. </div>
  722. <p>The <em>arg</em> argument must be a tuple object containing an argument list passed
  723. from Python to a C function. The <em>format</em> argument must be a format string,
  724. whose syntax is explained in <a class="reference internal" href="../c-api/arg.html#arg-parsing"><span class="std std-ref">Parsing arguments and building values</span></a> in the Python/C API Reference
  725. Manual. The remaining arguments must be addresses of variables whose type is
  726. determined by the format string.</p>
  727. <p>Note that while <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> checks that the Python arguments have
  728. the required types, it cannot check the validity of the addresses of C variables
  729. passed to the call: if you make mistakes there, your code will probably crash or
  730. at least overwrite random bits in memory. So be careful!</p>
  731. <p>Note that any Python object references which are provided to the caller are
  732. <em>borrowed</em> references; do not decrement their reference count!</p>
  733. <p>Some example calls:</p>
  734. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define PY_SSIZE_T_CLEAN </span><span class="cm">/* Make &quot;s#&quot; use Py_ssize_t rather than int. */</span>
  735. <span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;Python.h&gt;</span>
  736. </pre></div>
  737. </div>
  738. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span><span class="w"> </span><span class="n">ok</span><span class="p">;</span>
  739. <span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="p">,</span><span class="w"> </span><span class="n">j</span><span class="p">;</span>
  740. <span class="kt">long</span><span class="w"> </span><span class="n">k</span><span class="p">,</span><span class="w"> </span><span class="n">l</span><span class="p">;</span>
  741. <span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">;</span>
  742. <span class="n">Py_ssize_t</span><span class="w"> </span><span class="n">size</span><span class="p">;</span>
  743. <span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;&quot;</span><span class="p">);</span><span class="w"> </span><span class="cm">/* No arguments */</span>
  744. <span class="w"> </span><span class="cm">/* Python call: f() */</span>
  745. </pre></div>
  746. </div>
  747. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">s</span><span class="p">);</span><span class="w"> </span><span class="cm">/* A string */</span>
  748. <span class="w"> </span><span class="cm">/* Possible Python call: f(&#39;whoops!&#39;) */</span>
  749. </pre></div>
  750. </div>
  751. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;lls&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">k</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">l</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">s</span><span class="p">);</span><span class="w"> </span><span class="cm">/* Two longs and a string */</span>
  752. <span class="w"> </span><span class="cm">/* Possible Python call: f(1, 2, &#39;three&#39;) */</span>
  753. </pre></div>
  754. </div>
  755. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;(ii)s#&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">i</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">j</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">size</span><span class="p">);</span>
  756. <span class="w"> </span><span class="cm">/* A pair of ints and a string, whose size is also returned */</span>
  757. <span class="w"> </span><span class="cm">/* Possible Python call: f((1, 2), &#39;three&#39;) */</span>
  758. </pre></div>
  759. </div>
  760. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  761. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">file</span><span class="p">;</span>
  762. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">mode</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&quot;r&quot;</span><span class="p">;</span>
  763. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">bufsize</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
  764. <span class="w"> </span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s|si&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">file</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">mode</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">bufsize</span><span class="p">);</span>
  765. <span class="w"> </span><span class="cm">/* A string, and optionally another string and an integer */</span>
  766. <span class="w"> </span><span class="cm">/* Possible Python calls:</span>
  767. <span class="cm"> f(&#39;spam&#39;)</span>
  768. <span class="cm"> f(&#39;spam&#39;, &#39;w&#39;)</span>
  769. <span class="cm"> f(&#39;spam&#39;, &#39;wb&#39;, 100000) */</span>
  770. <span class="p">}</span>
  771. </pre></div>
  772. </div>
  773. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  774. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">left</span><span class="p">,</span><span class="w"> </span><span class="n">top</span><span class="p">,</span><span class="w"> </span><span class="n">right</span><span class="p">,</span><span class="w"> </span><span class="n">bottom</span><span class="p">,</span><span class="w"> </span><span class="n">h</span><span class="p">,</span><span class="w"> </span><span class="n">v</span><span class="p">;</span>
  775. <span class="w"> </span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;((ii)(ii))(ii)&quot;</span><span class="p">,</span>
  776. <span class="w"> </span><span class="o">&amp;</span><span class="n">left</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">top</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">right</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">bottom</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">h</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">v</span><span class="p">);</span>
  777. <span class="w"> </span><span class="cm">/* A rectangle and a point */</span>
  778. <span class="w"> </span><span class="cm">/* Possible Python call:</span>
  779. <span class="cm"> f(((0, 0), (400, 300)), (10, 10)) */</span>
  780. <span class="p">}</span>
  781. </pre></div>
  782. </div>
  783. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  784. <span class="w"> </span><span class="n">Py_complex</span><span class="w"> </span><span class="n">c</span><span class="p">;</span>
  785. <span class="w"> </span><span class="n">ok</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;D:myfunction&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">c</span><span class="p">);</span>
  786. <span class="w"> </span><span class="cm">/* a complex, also providing a function name for errors */</span>
  787. <span class="w"> </span><span class="cm">/* Possible Python call: myfunction(1+2j) */</span>
  788. <span class="p">}</span>
  789. </pre></div>
  790. </div>
  791. </section>
  792. <section id="keyword-parameters-for-extension-functions">
  793. <span id="parsetupleandkeywords"></span><h2><span class="section-number">1.8. </span>Keyword Parameters for Extension Functions<a class="headerlink" href="#keyword-parameters-for-extension-functions" title="Link to this heading">¶</a></h2>
  794. <p id="index-3">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> function is declared as follows:</p>
  795. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span><span class="w"> </span><span class="nf">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">arg</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">kwdict</span><span class="p">,</span>
  796. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">format</span><span class="p">,</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">kwlist</span><span class="p">[],</span><span class="w"> </span><span class="p">...);</span>
  797. </pre></div>
  798. </div>
  799. <p>The <em>arg</em> and <em>format</em> parameters are identical to those of the
  800. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function. The <em>kwdict</em> parameter is the dictionary of
  801. keywords received as the third parameter from the Python runtime. The <em>kwlist</em>
  802. parameter is a <code class="docutils literal notranslate"><span class="pre">NULL</span></code>-terminated list of strings which identify the parameters;
  803. the names are matched with the type information from <em>format</em> from left to
  804. right. On success, <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> returns true, otherwise
  805. it returns false and raises an appropriate exception.</p>
  806. <div class="admonition note">
  807. <p class="admonition-title">Note</p>
  808. <p>Nested tuples cannot be parsed when using keyword arguments! Keyword parameters
  809. passed in which are not present in the <em>kwlist</em> will cause <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to
  810. be raised.</p>
  811. </div>
  812. <p id="index-4">Here is an example module which uses keywords, based on an example by Geoff
  813. Philbrick (<a class="reference external" href="mailto:philbrick&#37;&#52;&#48;hks&#46;com">philbrick<span>&#64;</span>hks<span>&#46;</span>com</a>):</p>
  814. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define PY_SSIZE_T_CLEAN </span><span class="cm">/* Make &quot;s#&quot; use Py_ssize_t rather than int. */</span>
  815. <span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;Python.h&gt;</span>
  816. <span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  817. <span class="nf">keywdarg_parrot</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">keywds</span><span class="p">)</span>
  818. <span class="p">{</span>
  819. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">voltage</span><span class="p">;</span>
  820. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">state</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&quot;a stiff&quot;</span><span class="p">;</span>
  821. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">action</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&quot;voom&quot;</span><span class="p">;</span>
  822. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">type</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&quot;Norwegian Blue&quot;</span><span class="p">;</span>
  823. <span class="w"> </span><span class="k">static</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="s">&quot;voltage&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;state&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;action&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;type&quot;</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">};</span>
  824. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="n">keywds</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;i|sss&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">kwlist</span><span class="p">,</span>
  825. <span class="w"> </span><span class="o">&amp;</span><span class="n">voltage</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">state</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">action</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">type</span><span class="p">))</span>
  826. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  827. <span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">&quot;-- This parrot wouldn&#39;t %s if you put %i Volts through it.</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span>
  828. <span class="w"> </span><span class="n">action</span><span class="p">,</span><span class="w"> </span><span class="n">voltage</span><span class="p">);</span>
  829. <span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">&quot;-- Lovely plumage, the %s -- It&#39;s %s!</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">type</span><span class="p">,</span><span class="w"> </span><span class="n">state</span><span class="p">);</span>
  830. <span class="w"> </span><span class="n">Py_RETURN_NONE</span><span class="p">;</span>
  831. <span class="p">}</span>
  832. <span class="k">static</span><span class="w"> </span><span class="n">PyMethodDef</span><span class="w"> </span><span class="n">keywdarg_methods</span><span class="p">[]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
  833. <span class="w"> </span><span class="cm">/* The cast of the function is necessary since PyCFunction values</span>
  834. <span class="cm"> * only take two PyObject* parameters, and keywdarg_parrot() takes</span>
  835. <span class="cm"> * three.</span>
  836. <span class="cm"> */</span>
  837. <span class="w"> </span><span class="p">{</span><span class="s">&quot;parrot&quot;</span><span class="p">,</span><span class="w"> </span><span class="p">(</span><span class="n">PyCFunction</span><span class="p">)(</span><span class="kt">void</span><span class="p">(</span><span class="o">*</span><span class="p">)(</span><span class="kt">void</span><span class="p">))</span><span class="n">keywdarg_parrot</span><span class="p">,</span><span class="w"> </span><span class="n">METH_VARARGS</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="n">METH_KEYWORDS</span><span class="p">,</span>
  838. <span class="w"> </span><span class="s">&quot;Print a lovely skit to standard output.&quot;</span><span class="p">},</span>
  839. <span class="w"> </span><span class="p">{</span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">}</span><span class="w"> </span><span class="cm">/* sentinel */</span>
  840. <span class="p">};</span>
  841. <span class="k">static</span><span class="w"> </span><span class="k">struct</span><span class="w"> </span><span class="nc">PyModuleDef</span><span class="w"> </span><span class="n">keywdargmodule</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
  842. <span class="w"> </span><span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span>
  843. <span class="w"> </span><span class="s">&quot;keywdarg&quot;</span><span class="p">,</span>
  844. <span class="w"> </span><span class="nb">NULL</span><span class="p">,</span>
  845. <span class="w"> </span><span class="mi">-1</span><span class="p">,</span>
  846. <span class="w"> </span><span class="n">keywdarg_methods</span>
  847. <span class="p">};</span>
  848. <span class="n">PyMODINIT_FUNC</span>
  849. <span class="nf">PyInit_keywdarg</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  850. <span class="p">{</span>
  851. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">keywdargmodule</span><span class="p">);</span>
  852. <span class="p">}</span>
  853. </pre></div>
  854. </div>
  855. </section>
  856. <section id="building-arbitrary-values">
  857. <span id="buildvalue"></span><h2><span class="section-number">1.9. </span>Building Arbitrary Values<a class="headerlink" href="#building-arbitrary-values" title="Link to this heading">¶</a></h2>
  858. <p>This function is the counterpart to <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>. It is declared
  859. as follows:</p>
  860. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="nf">Py_BuildValue</span><span class="p">(</span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">format</span><span class="p">,</span><span class="w"> </span><span class="p">...);</span>
  861. </pre></div>
  862. </div>
  863. <p>It recognizes a set of format units similar to the ones recognized by
  864. <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>, but the arguments (which are input to the function,
  865. not output) must not be pointers, just values. It returns a new Python object,
  866. suitable for returning from a C function called from Python.</p>
  867. <p>One difference with <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>: while the latter requires its
  868. first argument to be a tuple (since Python argument lists are always represented
  869. as tuples internally), <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> does not always build a tuple. It
  870. builds a tuple only if its format string contains two or more format units. If
  871. the format string is empty, it returns <code class="docutils literal notranslate"><span class="pre">None</span></code>; if it contains exactly one
  872. format unit, it returns whatever object is described by that format unit. To
  873. force it to return a tuple of size 0 or one, parenthesize the format string.</p>
  874. <p>Examples (to the left the call, to the right the resulting Python value):</p>
  875. <div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Py_BuildValue(&quot;&quot;) None
  876. Py_BuildValue(&quot;i&quot;, 123) 123
  877. Py_BuildValue(&quot;iii&quot;, 123, 456, 789) (123, 456, 789)
  878. Py_BuildValue(&quot;s&quot;, &quot;hello&quot;) &#39;hello&#39;
  879. Py_BuildValue(&quot;y&quot;, &quot;hello&quot;) b&#39;hello&#39;
  880. Py_BuildValue(&quot;ss&quot;, &quot;hello&quot;, &quot;world&quot;) (&#39;hello&#39;, &#39;world&#39;)
  881. Py_BuildValue(&quot;s#&quot;, &quot;hello&quot;, 4) &#39;hell&#39;
  882. Py_BuildValue(&quot;y#&quot;, &quot;hello&quot;, 4) b&#39;hell&#39;
  883. Py_BuildValue(&quot;()&quot;) ()
  884. Py_BuildValue(&quot;(i)&quot;, 123) (123,)
  885. Py_BuildValue(&quot;(ii)&quot;, 123, 456) (123, 456)
  886. Py_BuildValue(&quot;(i,i)&quot;, 123, 456) (123, 456)
  887. Py_BuildValue(&quot;[i,i]&quot;, 123, 456) [123, 456]
  888. Py_BuildValue(&quot;{s:i,s:i}&quot;,
  889. &quot;abc&quot;, 123, &quot;def&quot;, 456) {&#39;abc&#39;: 123, &#39;def&#39;: 456}
  890. Py_BuildValue(&quot;((ii)(ii)) (ii)&quot;,
  891. 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
  892. </pre></div>
  893. </div>
  894. </section>
  895. <section id="reference-counts">
  896. <span id="refcounts"></span><h2><span class="section-number">1.10. </span>Reference Counts<a class="headerlink" href="#reference-counts" title="Link to this heading">¶</a></h2>
  897. <p>In languages like C or C++, the programmer is responsible for dynamic allocation
  898. and deallocation of memory on the heap. In C, this is done using the functions
  899. <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>. In C++, the operators <code class="docutils literal notranslate"><span class="pre">new</span></code> and
  900. <code class="docutils literal notranslate"><span class="pre">delete</span></code> are used with essentially the same meaning and we’ll restrict
  901. the following discussion to the C case.</p>
  902. <p>Every block of memory allocated with <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> should eventually be
  903. returned to the pool of available memory by exactly one call to <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.
  904. It is important to call <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> at the right time. If a block’s address
  905. is forgotten but <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> is not called for it, the memory it occupies
  906. cannot be reused until the program terminates. This is called a <em class="dfn">memory
  907. leak</em>. On the other hand, if a program calls <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> for a block and then
  908. continues to use the block, it creates a conflict with re-use of the block
  909. through another <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call. This is called <em class="dfn">using freed memory</em>.
  910. It has the same bad consequences as referencing uninitialized data — core
  911. dumps, wrong results, mysterious crashes.</p>
  912. <p>Common causes of memory leaks are unusual paths through the code. For instance,
  913. a function may allocate a block of memory, do some calculation, and then free
  914. the block again. Now a change in the requirements for the function may add a
  915. test to the calculation that detects an error condition and can return
  916. prematurely from the function. It’s easy to forget to free the allocated memory
  917. block when taking this premature exit, especially when it is added later to the
  918. code. Such leaks, once introduced, often go undetected for a long time: the
  919. error exit is taken only in a small fraction of all calls, and most modern
  920. machines have plenty of virtual memory, so the leak only becomes apparent in a
  921. long-running process that uses the leaking function frequently. Therefore, it’s
  922. important to prevent leaks from happening by having a coding convention or
  923. strategy that minimizes this kind of errors.</p>
  924. <p>Since Python makes heavy use of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>, it needs a
  925. strategy to avoid memory leaks as well as the use of freed memory. The chosen
  926. method is called <em class="dfn">reference counting</em>. The principle is simple: every
  927. object contains a counter, which is incremented when a reference to the object
  928. is stored somewhere, and which is decremented when a reference to it is deleted.
  929. When the counter reaches zero, the last reference to the object has been deleted
  930. and the object is freed.</p>
  931. <p>An alternative strategy is called <em class="dfn">automatic garbage collection</em>.
  932. (Sometimes, reference counting is also referred to as a garbage collection
  933. strategy, hence my use of “automatic” to distinguish the two.) The big
  934. advantage of automatic garbage collection is that the user doesn’t need to call
  935. <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> explicitly. (Another claimed advantage is an improvement in speed
  936. or memory usage — this is no hard fact however.) The disadvantage is that for
  937. C, there is no truly portable automatic garbage collector, while reference
  938. counting can be implemented portably (as long as the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>
  939. and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> are available — which the C Standard guarantees). Maybe some
  940. day a sufficiently portable automatic garbage collector will be available for C.
  941. Until then, we’ll have to live with reference counts.</p>
  942. <p>While Python uses the traditional reference counting implementation, it also
  943. offers a cycle detector that works to detect reference cycles. This allows
  944. applications to not worry about creating direct or indirect circular references;
  945. these are the weakness of garbage collection implemented using only reference
  946. counting. Reference cycles consist of objects which contain (possibly indirect)
  947. references to themselves, so that each object in the cycle has a reference count
  948. which is non-zero. Typical reference counting implementations are not able to
  949. reclaim the memory belonging to any objects in a reference cycle, or referenced
  950. from the objects in the cycle, even though there are no further references to
  951. the cycle itself.</p>
  952. <p>The cycle detector is able to detect garbage cycles and can reclaim them.
  953. The <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module exposes a way to run the detector (the
  954. <a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">collect()</span></code></a> function), as well as configuration
  955. interfaces and the ability to disable the detector at runtime.</p>
  956. <section id="reference-counting-in-python">
  957. <span id="refcountsinpython"></span><h3><span class="section-number">1.10.1. </span>Reference Counting in Python<a class="headerlink" href="#reference-counting-in-python" title="Link to this heading">¶</a></h3>
  958. <p>There are two macros, <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>, which handle the
  959. incrementing and decrementing of the reference count. <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> also
  960. frees the object when the count reaches zero. For flexibility, it doesn’t call
  961. <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> directly — rather, it makes a call through a function pointer in
  962. the object’s <em class="dfn">type object</em>. For this purpose (and others), every object
  963. also contains a pointer to its type object.</p>
  964. <p>The big question now remains: when to use <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>?
  965. Let’s first introduce some terms. Nobody “owns” an object; however, you can
  966. <em class="dfn">own a reference</em> to an object. An object’s reference count is now defined
  967. as the number of owned references to it. The owner of a reference is
  968. responsible for calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> when the reference is no longer
  969. needed. Ownership of a reference can be transferred. There are three ways to
  970. dispose of an owned reference: pass it on, store it, or call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>.
  971. Forgetting to dispose of an owned reference creates a memory leak.</p>
  972. <p>It is also possible to <em class="dfn">borrow</em> <a class="footnote-reference brackets" href="#id6" id="id2" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a> a reference to an object. The
  973. borrower of a reference should not call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>. The borrower must
  974. not hold on to the object longer than the owner from which it was borrowed.
  975. Using a borrowed reference after the owner has disposed of it risks using freed
  976. memory and should be avoided completely <a class="footnote-reference brackets" href="#id7" id="id3" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a>.</p>
  977. <p>The advantage of borrowing over owning a reference is that you don’t need to
  978. take care of disposing of the reference on all possible paths through the code
  979. — in other words, with a borrowed reference you don’t run the risk of leaking
  980. when a premature exit is taken. The disadvantage of borrowing over owning is
  981. that there are some subtle situations where in seemingly correct code a borrowed
  982. reference can be used after the owner from which it was borrowed has in fact
  983. disposed of it.</p>
  984. <p>A borrowed reference can be changed into an owned reference by calling
  985. <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>. This does not affect the status of the owner from which the
  986. reference was borrowed — it creates a new owned reference, and gives full
  987. owner responsibilities (the new owner must dispose of the reference properly, as
  988. well as the previous owner).</p>
  989. </section>
  990. <section id="ownership-rules">
  991. <span id="ownershiprules"></span><h3><span class="section-number">1.10.2. </span>Ownership Rules<a class="headerlink" href="#ownership-rules" title="Link to this heading">¶</a></h3>
  992. <p>Whenever an object reference is passed into or out of a function, it is part of
  993. the function’s interface specification whether ownership is transferred with the
  994. reference or not.</p>
  995. <p>Most functions that return a reference to an object pass on ownership with the
  996. reference. In particular, all functions whose function it is to create a new
  997. object, such as <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a> and <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, pass
  998. ownership to the receiver. Even if the object is not actually new, you still
  999. receive ownership of a new reference to that object. For instance,
  1000. <a class="reference internal" href="../c-api/long.html#c.PyLong_FromLong" title="PyLong_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromLong()</span></code></a> maintains a cache of popular values and can return a
  1001. reference to a cached item.</p>
  1002. <p>Many functions that extract objects from other objects also transfer ownership
  1003. with the reference, for instance <a class="reference internal" href="../c-api/object.html#c.PyObject_GetAttrString" title="PyObject_GetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetAttrString()</span></code></a>. The picture
  1004. is less clear, here, however, since a few common routines are exceptions:
  1005. <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItem" title="PyDict_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItem()</span></code></a>, and
  1006. <a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItemString" title="PyDict_GetItemString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItemString()</span></code></a> all return references that you borrow from the
  1007. tuple, list or dictionary.</p>
  1008. <p>The function <a class="reference internal" href="../c-api/import.html#c.PyImport_AddModule" title="PyImport_AddModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_AddModule()</span></code></a> also returns a borrowed reference, even
  1009. though it may actually create the object it returns: this is possible because an
  1010. owned reference to the object is stored in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
  1011. <p>When you pass an object reference into another function, in general, the
  1012. function borrows the reference from you — if it needs to store it, it will use
  1013. <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to become an independent owner. There are exactly two
  1014. important exceptions to this rule: <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> and
  1015. <a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>. These functions take over ownership of the item passed
  1016. to them — even if they fail! (Note that <a class="reference internal" href="../c-api/dict.html#c.PyDict_SetItem" title="PyDict_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_SetItem()</span></code></a> and friends
  1017. don’t take over ownership — they are “normal.”)</p>
  1018. <p>When a C function is called from Python, it borrows references to its arguments
  1019. from the caller. The caller owns a reference to the object, so the borrowed
  1020. reference’s lifetime is guaranteed until the function returns. Only when such a
  1021. borrowed reference must be stored or passed on, it must be turned into an owned
  1022. reference by calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>.</p>
  1023. <p>The object reference returned from a C function that is called from Python must
  1024. be an owned reference — ownership is transferred from the function to its
  1025. caller.</p>
  1026. </section>
  1027. <section id="thin-ice">
  1028. <span id="thinice"></span><h3><span class="section-number">1.10.3. </span>Thin Ice<a class="headerlink" href="#thin-ice" title="Link to this heading">¶</a></h3>
  1029. <p>There are a few situations where seemingly harmless use of a borrowed reference
  1030. can lead to problems. These all have to do with implicit invocations of the
  1031. interpreter, which can cause the owner of a reference to dispose of it.</p>
  1032. <p>The first and most important case to know about is using <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> on
  1033. an unrelated object while borrowing a reference to a list item. For instance:</p>
  1034. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
  1035. <span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">list</span><span class="p">)</span>
  1036. <span class="p">{</span>
  1037. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
  1038. <span class="w"> </span><span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mf">0L</span><span class="p">));</span>
  1039. <span class="w"> </span><span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span><span class="w"> </span><span class="n">stdout</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span><span class="w"> </span><span class="cm">/* BUG! */</span>
  1040. <span class="p">}</span>
  1041. </pre></div>
  1042. </div>
  1043. <p>This function first borrows a reference to <code class="docutils literal notranslate"><span class="pre">list[0]</span></code>, then replaces
  1044. <code class="docutils literal notranslate"><span class="pre">list[1]</span></code> with the value <code class="docutils literal notranslate"><span class="pre">0</span></code>, and finally prints the borrowed reference.
  1045. Looks harmless, right? But it’s not!</p>
  1046. <p>Let’s follow the control flow into <a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>. The list owns
  1047. references to all its items, so when item 1 is replaced, it has to dispose of
  1048. the original item 1. Now let’s suppose the original item 1 was an instance of a
  1049. user-defined class, and let’s further suppose that the class defined a
  1050. <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method. If this class instance has a reference count of 1,
  1051. disposing of it will call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method.</p>
  1052. <p>Since it is written in Python, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method can execute arbitrary
  1053. Python code. Could it perhaps do something to invalidate the reference to
  1054. <code class="docutils literal notranslate"><span class="pre">item</span></code> in <code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code>? You bet! Assuming that the list passed into
  1055. <code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code> is accessible to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> method, it could execute a
  1056. statement to the effect of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">list[0]</span></code>, and assuming this was the last
  1057. reference to that object, it would free the memory associated with it, thereby
  1058. invalidating <code class="docutils literal notranslate"><span class="pre">item</span></code>.</p>
  1059. <p>The solution, once you know the source of the problem, is easy: temporarily
  1060. increment the reference count. The correct version of the function reads:</p>
  1061. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
  1062. <span class="nf">no_bug</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">list</span><span class="p">)</span>
  1063. <span class="p">{</span>
  1064. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
  1065. <span class="w"> </span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
  1066. <span class="w"> </span><span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span><span class="w"> </span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="mf">0L</span><span class="p">));</span>
  1067. <span class="w"> </span><span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span><span class="w"> </span><span class="n">stdout</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
  1068. <span class="w"> </span><span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
  1069. <span class="p">}</span>
  1070. </pre></div>
  1071. </div>
  1072. <p>This is a true story. An older version of Python contained variants of this bug
  1073. and someone spent a considerable amount of time in a C debugger to figure out
  1074. why his <code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code> methods would fail…</p>
  1075. <p>The second case of problems with a borrowed reference is a variant involving
  1076. threads. Normally, multiple threads in the Python interpreter can’t get in each
  1077. other’s way, because there is a global lock protecting Python’s entire object
  1078. space. However, it is possible to temporarily release this lock using the macro
  1079. <a class="reference internal" href="../c-api/init.html#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a>, and to re-acquire it using
  1080. <a class="reference internal" href="../c-api/init.html#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a>. This is common around blocking I/O calls, to
  1081. let other threads use the processor while waiting for the I/O to complete.
  1082. Obviously, the following function has the same problem as the previous one:</p>
  1083. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
  1084. <span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">list</span><span class="p">)</span>
  1085. <span class="p">{</span>
  1086. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
  1087. <span class="w"> </span><span class="n">Py_BEGIN_ALLOW_THREADS</span>
  1088. <span class="w"> </span><span class="p">...</span><span class="n">some</span><span class="w"> </span><span class="n">blocking</span><span class="w"> </span><span class="n">I</span><span class="o">/</span><span class="n">O</span><span class="w"> </span><span class="n">call</span><span class="p">...</span>
  1089. <span class="w"> </span><span class="n">Py_END_ALLOW_THREADS</span>
  1090. <span class="w"> </span><span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span><span class="w"> </span><span class="n">stdout</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span><span class="w"> </span><span class="cm">/* BUG! */</span>
  1091. <span class="p">}</span>
  1092. </pre></div>
  1093. </div>
  1094. </section>
  1095. <section id="null-pointers">
  1096. <span id="nullpointers"></span><h3><span class="section-number">1.10.4. </span>NULL Pointers<a class="headerlink" href="#null-pointers" title="Link to this heading">¶</a></h3>
  1097. <p>In general, functions that take object references as arguments do not expect you
  1098. to pass them <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointers, and will dump core (or cause later core dumps) if
  1099. you do so. Functions that return object references generally return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> only
  1100. to indicate that an exception occurred. The reason for not testing for <code class="docutils literal notranslate"><span class="pre">NULL</span></code>
  1101. arguments is that functions often pass the objects they receive on to other
  1102. function — if each function were to test for <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, there would be a lot of
  1103. redundant tests and the code would run more slowly.</p>
  1104. <p>It is better to test for <code class="docutils literal notranslate"><span class="pre">NULL</span></code> only at the “source:” when a pointer that may be
  1105. <code class="docutils literal notranslate"><span class="pre">NULL</span></code> is received, for example, from <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> or from a function that
  1106. may raise an exception.</p>
  1107. <p>The macros <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> do not check for <code class="docutils literal notranslate"><span class="pre">NULL</span></code>
  1108. pointers — however, their variants <a class="reference internal" href="../c-api/refcounting.html#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>
  1109. do.</p>
  1110. <p>The macros for checking for a particular object type (<code class="docutils literal notranslate"><span class="pre">Pytype_Check()</span></code>) don’t
  1111. check for <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointers — again, there is much code that calls several of
  1112. these in a row to test an object against various different expected types, and
  1113. this would generate redundant tests. There are no variants with <code class="docutils literal notranslate"><span class="pre">NULL</span></code>
  1114. checking.</p>
  1115. <p>The C function calling mechanism guarantees that the argument list passed to C
  1116. functions (<code class="docutils literal notranslate"><span class="pre">args</span></code> in the examples) is never <code class="docutils literal notranslate"><span class="pre">NULL</span></code> — in fact it guarantees
  1117. that it is always a tuple <a class="footnote-reference brackets" href="#id8" id="id4" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a>.</p>
  1118. <p>It is a severe error to ever let a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointer “escape” to the Python user.</p>
  1119. </section>
  1120. </section>
  1121. <section id="writing-extensions-in-c">
  1122. <span id="cplusplus"></span><h2><span class="section-number">1.11. </span>Writing Extensions in C++<a class="headerlink" href="#writing-extensions-in-c" title="Link to this heading">¶</a></h2>
  1123. <p>It is possible to write extension modules in C++. Some restrictions apply. If
  1124. the main program (the Python interpreter) is compiled and linked by the C
  1125. compiler, global or static objects with constructors cannot be used. This is
  1126. not a problem if the main program is linked by the C++ compiler. Functions that
  1127. will be called by the Python interpreter (in particular, module initialization
  1128. functions) have to be declared using <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>. It is unnecessary to
  1129. enclose the Python header files in <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span> <span class="pre">{...}</span></code> — they use this form
  1130. already if the symbol <code class="docutils literal notranslate"><span class="pre">__cplusplus</span></code> is defined (all recent C++ compilers
  1131. define this symbol).</p>
  1132. </section>
  1133. <section id="providing-a-c-api-for-an-extension-module">
  1134. <span id="using-capsules"></span><h2><span class="section-number">1.12. </span>Providing a C API for an Extension Module<a class="headerlink" href="#providing-a-c-api-for-an-extension-module" title="Link to this heading">¶</a></h2>
  1135. <p>Many extension modules just provide new functions and types to be used from
  1136. Python, but sometimes the code in an extension module can be useful for other
  1137. extension modules. For example, an extension module could implement a type
  1138. “collection” which works like lists without order. Just like the standard Python
  1139. list type has a C API which permits extension modules to create and manipulate
  1140. lists, this new collection type should have a set of C functions for direct
  1141. manipulation from other extension modules.</p>
  1142. <p>At first sight this seems easy: just write the functions (without declaring them
  1143. <code class="docutils literal notranslate"><span class="pre">static</span></code>, of course), provide an appropriate header file, and document
  1144. the C API. And in fact this would work if all extension modules were always
  1145. linked statically with the Python interpreter. When modules are used as shared
  1146. libraries, however, the symbols defined in one module may not be visible to
  1147. another module. The details of visibility depend on the operating system; some
  1148. systems use one global namespace for the Python interpreter and all extension
  1149. modules (Windows, for example), whereas others require an explicit list of
  1150. imported symbols at module link time (AIX is one example), or offer a choice of
  1151. different strategies (most Unices). And even if symbols are globally visible,
  1152. the module whose functions one wishes to call might not have been loaded yet!</p>
  1153. <p>Portability therefore requires not to make any assumptions about symbol
  1154. visibility. This means that all symbols in extension modules should be declared
  1155. <code class="docutils literal notranslate"><span class="pre">static</span></code>, except for the module’s initialization function, in order to
  1156. avoid name clashes with other extension modules (as discussed in section
  1157. <a class="reference internal" href="#methodtable"><span class="std std-ref">The Module’s Method Table and Initialization Function</span></a>). And it means that symbols that <em>should</em> be accessible from
  1158. other extension modules must be exported in a different way.</p>
  1159. <p>Python provides a special mechanism to pass C-level information (pointers) from
  1160. one extension module to another one: Capsules. A Capsule is a Python data type
  1161. which stores a pointer (<span class="c-expr sig sig-inline c"><span class="kt">void</span><span class="p">*</span></span>). Capsules can only be created and
  1162. accessed via their C API, but they can be passed around like any other Python
  1163. object. In particular, they can be assigned to a name in an extension module’s
  1164. namespace. Other extension modules can then import this module, retrieve the
  1165. value of this name, and then retrieve the pointer from the Capsule.</p>
  1166. <p>There are many ways in which Capsules can be used to export the C API of an
  1167. extension module. Each function could get its own Capsule, or all C API pointers
  1168. could be stored in an array whose address is published in a Capsule. And the
  1169. various tasks of storing and retrieving the pointers can be distributed in
  1170. different ways between the module providing the code and the client modules.</p>
  1171. <p>Whichever method you choose, it’s important to name your Capsules properly.
  1172. The function <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_New" title="PyCapsule_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_New()</span></code></a> takes a name parameter
  1173. (<span class="c-expr sig sig-inline c"><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="p">*</span></span>); you’re permitted to pass in a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> name, but
  1174. we strongly encourage you to specify a name. Properly named Capsules provide
  1175. a degree of runtime type-safety; there is no feasible way to tell one unnamed
  1176. Capsule from another.</p>
  1177. <p>In particular, Capsules used to expose C APIs should be given a name following
  1178. this convention:</p>
  1179. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">modulename</span><span class="p">.</span><span class="n">attributename</span>
  1180. </pre></div>
  1181. </div>
  1182. <p>The convenience function <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_Import" title="PyCapsule_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_Import()</span></code></a> makes it easy to
  1183. load a C API provided via a Capsule, but only if the Capsule’s name
  1184. matches this convention. This behavior gives C API users a high degree
  1185. of certainty that the Capsule they load contains the correct C API.</p>
  1186. <p>The following example demonstrates an approach that puts most of the burden on
  1187. the writer of the exporting module, which is appropriate for commonly used
  1188. library modules. It stores all C API pointers (just one in the example!) in an
  1189. array of <span class="c-expr sig sig-inline c"><span class="kt">void</span></span> pointers which becomes the value of a Capsule. The header
  1190. file corresponding to the module provides a macro that takes care of importing
  1191. the module and retrieving its C API pointers; client modules only have to call
  1192. this macro before accessing the C API.</p>
  1193. <p>The exporting module is a modification of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> module from section
  1194. <a class="reference internal" href="#extending-simpleexample"><span class="std std-ref">A Simple Example</span></a>. The function <code class="xref py py-func docutils literal notranslate"><span class="pre">spam.system()</span></code> does not call
  1195. the C library function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> directly, but a function
  1196. <code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code>, which would of course do something more complicated in
  1197. reality (such as adding “spam” to every command). This function
  1198. <code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is also exported to other extension modules.</p>
  1199. <p>The function <code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is a plain C function, declared
  1200. <code class="docutils literal notranslate"><span class="pre">static</span></code> like everything else:</p>
  1201. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="kt">int</span>
  1202. <span class="nf">PySpam_System</span><span class="p">(</span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">command</span><span class="p">)</span>
  1203. <span class="p">{</span>
  1204. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
  1205. <span class="p">}</span>
  1206. </pre></div>
  1207. </div>
  1208. <p>The function <code class="xref c c-func docutils literal notranslate"><span class="pre">spam_system()</span></code> is modified in a trivial way:</p>
  1209. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
  1210. <span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">self</span><span class="p">,</span><span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  1211. <span class="p">{</span>
  1212. <span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">command</span><span class="p">;</span>
  1213. <span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">sts</span><span class="p">;</span>
  1214. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;s&quot;</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
  1215. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  1216. <span class="w"> </span><span class="n">sts</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PySpam_System</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
  1217. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
  1218. <span class="p">}</span>
  1219. </pre></div>
  1220. </div>
  1221. <p>In the beginning of the module, right after the line</p>
  1222. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;Python.h&gt;</span>
  1223. </pre></div>
  1224. </div>
  1225. <p>two more lines must be added:</p>
  1226. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define SPAM_MODULE</span>
  1227. <span class="cp">#include</span><span class="w"> </span><span class="cpf">&quot;spammodule.h&quot;</span>
  1228. </pre></div>
  1229. </div>
  1230. <p>The <code class="docutils literal notranslate"><span class="pre">#define</span></code> is used to tell the header file that it is being included in the
  1231. exporting module, not a client module. Finally, the module’s initialization
  1232. function must take care of initializing the C API pointer array:</p>
  1233. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
  1234. <span class="nf">PyInit_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  1235. <span class="p">{</span>
  1236. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">m</span><span class="p">;</span>
  1237. <span class="w"> </span><span class="k">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="o">*</span><span class="n">PySpam_API</span><span class="p">[</span><span class="n">PySpam_API_pointers</span><span class="p">];</span>
  1238. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">c_api_object</span><span class="p">;</span>
  1239. <span class="w"> </span><span class="n">m</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">spammodule</span><span class="p">);</span>
  1240. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">m</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  1241. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  1242. <span class="w"> </span><span class="cm">/* Initialize the C API pointer array */</span>
  1243. <span class="w"> </span><span class="n">PySpam_API</span><span class="p">[</span><span class="n">PySpam_System_NUM</span><span class="p">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="kt">void</span><span class="w"> </span><span class="o">*</span><span class="p">)</span><span class="n">PySpam_System</span><span class="p">;</span>
  1244. <span class="w"> </span><span class="cm">/* Create a Capsule containing the API pointer array&#39;s address */</span>
  1245. <span class="w"> </span><span class="n">c_api_object</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyCapsule_New</span><span class="p">((</span><span class="kt">void</span><span class="w"> </span><span class="o">*</span><span class="p">)</span><span class="n">PySpam_API</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;spam._C_API&quot;</span><span class="p">,</span><span class="w"> </span><span class="nb">NULL</span><span class="p">);</span>
  1246. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;_C_API&quot;</span><span class="p">,</span><span class="w"> </span><span class="n">c_api_object</span><span class="p">)</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
  1247. <span class="w"> </span><span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">c_api_object</span><span class="p">);</span>
  1248. <span class="w"> </span><span class="n">Py_DECREF</span><span class="p">(</span><span class="n">m</span><span class="p">);</span>
  1249. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  1250. <span class="w"> </span><span class="p">}</span>
  1251. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">m</span><span class="p">;</span>
  1252. <span class="p">}</span>
  1253. </pre></div>
  1254. </div>
  1255. <p>Note that <code class="docutils literal notranslate"><span class="pre">PySpam_API</span></code> is declared <code class="docutils literal notranslate"><span class="pre">static</span></code>; otherwise the pointer
  1256. array would disappear when <code class="xref c c-func docutils literal notranslate"><span class="pre">PyInit_spam()</span></code> terminates!</p>
  1257. <p>The bulk of the work is in the header file <code class="file docutils literal notranslate"><span class="pre">spammodule.h</span></code>, which looks
  1258. like this:</p>
  1259. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#ifndef Py_SPAMMODULE_H</span>
  1260. <span class="cp">#define Py_SPAMMODULE_H</span>
  1261. <span class="cp">#ifdef __cplusplus</span>
  1262. <span class="k">extern</span><span class="w"> </span><span class="s">&quot;C&quot;</span><span class="w"> </span><span class="p">{</span>
  1263. <span class="cp">#endif</span>
  1264. <span class="cm">/* Header file for spammodule */</span>
  1265. <span class="cm">/* C API functions */</span>
  1266. <span class="cp">#define PySpam_System_NUM 0</span>
  1267. <span class="cp">#define PySpam_System_RETURN int</span>
  1268. <span class="cp">#define PySpam_System_PROTO (const char *command)</span>
  1269. <span class="cm">/* Total number of C API pointers */</span>
  1270. <span class="cp">#define PySpam_API_pointers 1</span>
  1271. <span class="cp">#ifdef SPAM_MODULE</span>
  1272. <span class="cm">/* This section is used when compiling spammodule.c */</span>
  1273. <span class="k">static</span><span class="w"> </span><span class="n">PySpam_System_RETURN</span><span class="w"> </span><span class="n">PySpam_System</span><span class="w"> </span><span class="n">PySpam_System_PROTO</span><span class="p">;</span>
  1274. <span class="cp">#else</span>
  1275. <span class="cm">/* This section is used in modules that use spammodule&#39;s API */</span>
  1276. <span class="k">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="o">**</span><span class="n">PySpam_API</span><span class="p">;</span>
  1277. <span class="cp">#define PySpam_System \</span>
  1278. <span class="cp"> (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])</span>
  1279. <span class="cm">/* Return -1 on error, 0 on success.</span>
  1280. <span class="cm"> * PyCapsule_Import will set an exception if there&#39;s an error.</span>
  1281. <span class="cm"> */</span>
  1282. <span class="k">static</span><span class="w"> </span><span class="kt">int</span>
  1283. <span class="nf">import_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  1284. <span class="p">{</span>
  1285. <span class="w"> </span><span class="n">PySpam_API</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="kt">void</span><span class="w"> </span><span class="o">**</span><span class="p">)</span><span class="n">PyCapsule_Import</span><span class="p">(</span><span class="s">&quot;spam._C_API&quot;</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
  1286. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">(</span><span class="n">PySpam_API</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="o">?</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="o">:</span><span class="w"> </span><span class="mi">-1</span><span class="p">;</span>
  1287. <span class="p">}</span>
  1288. <span class="cp">#endif</span>
  1289. <span class="cp">#ifdef __cplusplus</span>
  1290. <span class="p">}</span>
  1291. <span class="cp">#endif</span>
  1292. <span class="cp">#endif </span><span class="cm">/* !defined(Py_SPAMMODULE_H) */</span>
  1293. </pre></div>
  1294. </div>
  1295. <p>All that a client module must do in order to have access to the function
  1296. <code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is to call the function (or rather macro)
  1297. <code class="xref c c-func docutils literal notranslate"><span class="pre">import_spam()</span></code> in its initialization function:</p>
  1298. <div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
  1299. <span class="nf">PyInit_client</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
  1300. <span class="p">{</span>
  1301. <span class="w"> </span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">m</span><span class="p">;</span>
  1302. <span class="w"> </span><span class="n">m</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">clientmodule</span><span class="p">);</span>
  1303. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">m</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span>
  1304. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  1305. <span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">import_spam</span><span class="p">()</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">0</span><span class="p">)</span>
  1306. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span>
  1307. <span class="w"> </span><span class="cm">/* additional initialization can happen here */</span>
  1308. <span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">m</span><span class="p">;</span>
  1309. <span class="p">}</span>
  1310. </pre></div>
  1311. </div>
  1312. <p>The main disadvantage of this approach is that the file <code class="file docutils literal notranslate"><span class="pre">spammodule.h</span></code> is
  1313. rather complicated. However, the basic structure is the same for each function
  1314. that is exported, so it has to be learned only once.</p>
  1315. <p>Finally it should be mentioned that Capsules offer additional functionality,
  1316. which is especially useful for memory allocation and deallocation of the pointer
  1317. stored in a Capsule. The details are described in the Python/C API Reference
  1318. Manual in the section <a class="reference internal" href="../c-api/capsule.html#capsules"><span class="std std-ref">Capsules</span></a> and in the implementation of Capsules (files
  1319. <code class="file docutils literal notranslate"><span class="pre">Include/pycapsule.h</span></code> and <code class="file docutils literal notranslate"><span class="pre">Objects/pycapsule.c</span></code> in the Python source
  1320. code distribution).</p>
  1321. <p class="rubric">Footnotes</p>
  1322. <aside class="footnote-list brackets">
  1323. <aside class="footnote brackets" id="id5" role="doc-footnote">
  1324. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
  1325. <p>An interface for this function already exists in the standard module <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>
  1326. — it was chosen as a simple and straightforward example.</p>
  1327. </aside>
  1328. <aside class="footnote brackets" id="id6" role="doc-footnote">
  1329. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id2">2</a><span class="fn-bracket">]</span></span>
  1330. <p>The metaphor of “borrowing” a reference is not completely correct: the owner
  1331. still has a copy of the reference.</p>
  1332. </aside>
  1333. <aside class="footnote brackets" id="id7" role="doc-footnote">
  1334. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id3">3</a><span class="fn-bracket">]</span></span>
  1335. <p>Checking that the reference count is at least 1 <strong>does not work</strong> — the
  1336. reference count itself could be in freed memory and may thus be reused for
  1337. another object!</p>
  1338. </aside>
  1339. <aside class="footnote brackets" id="id8" role="doc-footnote">
  1340. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id4">4</a><span class="fn-bracket">]</span></span>
  1341. <p>These guarantees don’t hold when you use the “old” style calling convention —
  1342. this is still found in much existing code.</p>
  1343. </aside>
  1344. </aside>
  1345. </section>
  1346. </section>
  1347. <div class="clearer"></div>
  1348. </div>
  1349. </div>
  1350. </div>
  1351. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  1352. <div class="sphinxsidebarwrapper">
  1353. <div>
  1354. <h3><a href="../contents.html">Table of Contents</a></h3>
  1355. <ul>
  1356. <li><a class="reference internal" href="#">1. Extending Python with C or C++</a><ul>
  1357. <li><a class="reference internal" href="#a-simple-example">1.1. A Simple Example</a></li>
  1358. <li><a class="reference internal" href="#intermezzo-errors-and-exceptions">1.2. Intermezzo: Errors and Exceptions</a></li>
  1359. <li><a class="reference internal" href="#back-to-the-example">1.3. Back to the Example</a></li>
  1360. <li><a class="reference internal" href="#the-module-s-method-table-and-initialization-function">1.4. The Module’s Method Table and Initialization Function</a></li>
  1361. <li><a class="reference internal" href="#compilation-and-linkage">1.5. Compilation and Linkage</a></li>
  1362. <li><a class="reference internal" href="#calling-python-functions-from-c">1.6. Calling Python Functions from C</a></li>
  1363. <li><a class="reference internal" href="#extracting-parameters-in-extension-functions">1.7. Extracting Parameters in Extension Functions</a></li>
  1364. <li><a class="reference internal" href="#keyword-parameters-for-extension-functions">1.8. Keyword Parameters for Extension Functions</a></li>
  1365. <li><a class="reference internal" href="#building-arbitrary-values">1.9. Building Arbitrary Values</a></li>
  1366. <li><a class="reference internal" href="#reference-counts">1.10. Reference Counts</a><ul>
  1367. <li><a class="reference internal" href="#reference-counting-in-python">1.10.1. Reference Counting in Python</a></li>
  1368. <li><a class="reference internal" href="#ownership-rules">1.10.2. Ownership Rules</a></li>
  1369. <li><a class="reference internal" href="#thin-ice">1.10.3. Thin Ice</a></li>
  1370. <li><a class="reference internal" href="#null-pointers">1.10.4. NULL Pointers</a></li>
  1371. </ul>
  1372. </li>
  1373. <li><a class="reference internal" href="#writing-extensions-in-c">1.11. Writing Extensions in C++</a></li>
  1374. <li><a class="reference internal" href="#providing-a-c-api-for-an-extension-module">1.12. Providing a C API for an Extension Module</a></li>
  1375. </ul>
  1376. </li>
  1377. </ul>
  1378. </div>
  1379. <div>
  1380. <h4>Previous topic</h4>
  1381. <p class="topless"><a href="index.html"
  1382. title="previous chapter">Extending and Embedding the Python Interpreter</a></p>
  1383. </div>
  1384. <div>
  1385. <h4>Next topic</h4>
  1386. <p class="topless"><a href="newtypes_tutorial.html"
  1387. title="next chapter"><span class="section-number">2. </span>Defining Extension Types: Tutorial</a></p>
  1388. </div>
  1389. <div role="note" aria-label="source link">
  1390. <h3>This Page</h3>
  1391. <ul class="this-page-menu">
  1392. <li><a href="../bugs.html">Report a Bug</a></li>
  1393. <li>
  1394. <a href="https://github.com/python/cpython/blob/main/Doc/extending/extending.rst"
  1395. rel="nofollow">Show Source
  1396. </a>
  1397. </li>
  1398. </ul>
  1399. </div>
  1400. </div>
  1401. <div id="sidebarbutton" title="Collapse sidebar">
  1402. <span>«</span>
  1403. </div>
  1404. </div>
  1405. <div class="clearer"></div>
  1406. </div>
  1407. <div class="related" role="navigation" aria-label="related navigation">
  1408. <h3>Navigation</h3>
  1409. <ul>
  1410. <li class="right" style="margin-right: 10px">
  1411. <a href="../genindex.html" title="General Index"
  1412. >index</a></li>
  1413. <li class="right" >
  1414. <a href="../py-modindex.html" title="Python Module Index"
  1415. >modules</a> |</li>
  1416. <li class="right" >
  1417. <a href="newtypes_tutorial.html" title="2. Defining Extension Types: Tutorial"
  1418. >next</a> |</li>
  1419. <li class="right" >
  1420. <a href="index.html" title="Extending and Embedding the Python Interpreter"
  1421. >previous</a> |</li>
  1422. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  1423. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  1424. <li class="switchers">
  1425. <div class="language_switcher_placeholder"></div>
  1426. <div class="version_switcher_placeholder"></div>
  1427. </li>
  1428. <li>
  1429. </li>
  1430. <li id="cpython-language-and-version">
  1431. <a href="../index.html">3.12.3 Documentation</a> &#187;
  1432. </li>
  1433. <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li>
  1434. <li class="nav-item nav-item-this"><a href=""><span class="section-number">1. </span>Extending Python with C or C++</a></li>
  1435. <li class="right">
  1436. <div class="inline-search" role="search">
  1437. <form class="inline-search" action="../search.html" method="get">
  1438. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  1439. <input type="submit" value="Go" />
  1440. </form>
  1441. </div>
  1442. |
  1443. </li>
  1444. <li class="right">
  1445. <label class="theme-selector-label">
  1446. Theme
  1447. <select class="theme-selector" oninput="activateTheme(this.value)">
  1448. <option value="auto" selected>Auto</option>
  1449. <option value="light">Light</option>
  1450. <option value="dark">Dark</option>
  1451. </select>
  1452. </label> |</li>
  1453. </ul>
  1454. </div>
  1455. <div class="footer">
  1456. &copy;
  1457. <a href="../copyright.html">
  1458. Copyright
  1459. </a>
  1460. 2001-2024, Python Software Foundation.
  1461. <br />
  1462. This page is licensed under the Python Software Foundation License Version 2.
  1463. <br />
  1464. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  1465. <br />
  1466. See <a href="/license.html">History and License</a> for more information.<br />
  1467. <br />
  1468. The Python Software Foundation is a non-profit corporation.
  1469. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  1470. <br />
  1471. <br />
  1472. Last updated on Apr 09, 2024 (13:47 UTC).
  1473. <a href="/bugs.html">Found a bug</a>?
  1474. <br />
  1475. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  1476. </div>
  1477. </body>
  1478. </html>
上海开阖软件有限公司 沪ICP备12045867号-1