Sophie

Sophie

distrib > Mandriva > 2010.1 > x86_64 > media > contrib-backports > by-pkgid > 3ba3bd1608c672ba2129b098a48e9e4d > files > 647

python3-docs-3.2.2-3mdv2010.2.noarch.rpm



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>15.17. ctypes — A foreign function library for Python &mdash; Python v3.2.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.2.2',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v3.2.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v3.2.2 documentation" href="../index.html" />
    <link rel="up" title="15. Generic Operating System Services" href="allos.html" />
    <link rel="next" title="16. Optional Operating System Services" href="someos.html" />
    <link rel="prev" title="15.16. errno — Standard errno system symbols" href="errno.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-ctypes">
<span id="ctypes-a-foreign-function-library-for-python"></span><h1>15.17. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> &#8212; A foreign function library for Python<a class="headerlink" href="#module-ctypes" title="Permalink to this headline">¶</a></h1>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> is a foreign function library for Python.  It provides C compatible
data types, and allows calling functions in DLLs or shared libraries.  It can be
used to wrap these libraries in pure Python.</p>
<div class="section" id="ctypes-tutorial">
<span id="ctypes-ctypes-tutorial"></span><h2>15.17.1. ctypes tutorial<a class="headerlink" href="#ctypes-tutorial" title="Permalink to this headline">¶</a></h2>
<p>Note: The code samples in this tutorial use <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><tt class="xref py py-mod docutils literal"><span class="pre">doctest</span></tt></a> to make sure that
they actually work.  Since some code samples behave differently under Linux,
Windows, or Mac OS X, they contain doctest directives in comments.</p>
<p>Note: Some code samples reference the ctypes <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a> type. This type is
an alias for the <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><tt class="xref py py-class docutils literal"><span class="pre">c_long</span></tt></a> type on 32-bit systems.  So, you should not be
confused if <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><tt class="xref py py-class docutils literal"><span class="pre">c_long</span></tt></a> is printed if you would expect <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a> &#8212;
they are actually the same type.</p>
<div class="section" id="loading-dynamic-link-libraries">
<span id="ctypes-loading-dynamic-link-libraries"></span><h3>15.17.1.1. Loading dynamic link libraries<a class="headerlink" href="#loading-dynamic-link-libraries" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> exports the <em>cdll</em>, and on Windows <em>windll</em> and <em>oledll</em>
objects, for loading dynamic link libraries.</p>
<p>You load libraries by accessing them as attributes of these objects. <em>cdll</em>
loads libraries which export functions using the standard <tt class="docutils literal"><span class="pre">cdecl</span></tt> calling
convention, while <em>windll</em> libraries call functions using the <tt class="docutils literal"><span class="pre">stdcall</span></tt>
calling convention. <em>oledll</em> also uses the <tt class="docutils literal"><span class="pre">stdcall</span></tt> calling convention, and
assumes the functions return a Windows <tt class="xref c c-type docutils literal"><span class="pre">HRESULT</span></tt> error code. The error
code is used to automatically raise a <a class="reference internal" href="exceptions.html#WindowsError" title="WindowsError"><tt class="xref py py-class docutils literal"><span class="pre">WindowsError</span></tt></a> exception when the
function call fails.</p>
<p>Here are some examples for Windows. Note that <tt class="docutils literal"><span class="pre">msvcrt</span></tt> is the MS standard C
library containing most standard C functions, and uses the cdecl calling
convention:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="p">)</span> 
<span class="go">&lt;WinDLL &#39;kernel32&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span><span class="p">)</span> 
<span class="go">&lt;CDLL &#39;msvcrt&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span> <span class="o">=</span> <span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span> 
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Windows appends the usual <tt class="docutils literal"><span class="pre">.dll</span></tt> file suffix automatically.</p>
<p>On Linux, it is required to specify the filename <em>including</em> the extension to
load a library, so attribute access can not be used to load libraries. Either the
<tt class="xref py py-meth docutils literal"><span class="pre">LoadLibrary()</span></tt> method of the dll loaders should be used, or you should load
the library by creating an instance of CDLL by calling the constructor:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">LoadLibrary</span><span class="p">(</span><span class="s">&quot;libc.so.6&quot;</span><span class="p">)</span> 
<span class="go">&lt;CDLL &#39;libc.so.6&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span> <span class="o">=</span> <span class="n">CDLL</span><span class="p">(</span><span class="s">&quot;libc.so.6&quot;</span><span class="p">)</span>     
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span>                         
<span class="go">&lt;CDLL &#39;libc.so.6&#39;, handle ... at ...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="accessing-functions-from-loaded-dlls">
<span id="ctypes-accessing-functions-from-loaded-dlls"></span><h3>15.17.1.2. Accessing functions from loaded dlls<a class="headerlink" href="#accessing-functions-from-loaded-dlls" title="Permalink to this headline">¶</a></h3>
<p>Functions are accessed as attributes of dll objects:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">printf</span>
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">)</span> 
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">MyOwnFunction</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
  File <span class="nb">&quot;ctypes.py&quot;</span>, line <span class="m">239</span>, in <span class="n-Identifier">__getattr__</span>
    <span class="n">func</span> <span class="o">=</span> <span class="n">_StdcallFuncPtr</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="nc">AttributeError</span>: <span class="n-Identifier">function &#39;MyOwnFunction&#39; not found</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that win32 system dlls like <tt class="docutils literal"><span class="pre">kernel32</span></tt> and <tt class="docutils literal"><span class="pre">user32</span></tt> often export ANSI
as well as UNICODE versions of a function. The UNICODE version is exported with
an <tt class="docutils literal"><span class="pre">W</span></tt> appended to the name, while the ANSI version is exported with an <tt class="docutils literal"><span class="pre">A</span></tt>
appended to the name. The win32 <tt class="docutils literal"><span class="pre">GetModuleHandle</span></tt> function, which returns a
<em>module handle</em> for a given module name, has the following C prototype, and a
macro is used to expose one of them as <tt class="docutils literal"><span class="pre">GetModuleHandle</span></tt> depending on whether
UNICODE is defined or not:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="o">/*</span> <span class="n">ANSI</span> <span class="n">version</span> <span class="o">*/</span>
<span class="n">HMODULE</span> <span class="n">GetModuleHandleA</span><span class="p">(</span><span class="n">LPCSTR</span> <span class="n">lpModuleName</span><span class="p">);</span>
<span class="o">/*</span> <span class="n">UNICODE</span> <span class="n">version</span> <span class="o">*/</span>
<span class="n">HMODULE</span> <span class="n">GetModuleHandleW</span><span class="p">(</span><span class="n">LPCWSTR</span> <span class="n">lpModuleName</span><span class="p">);</span>
</pre></div>
</div>
<p><em>windll</em> does not try to select one of them by magic, you must access the
version you need by specifying <tt class="docutils literal"><span class="pre">GetModuleHandleA</span></tt> or <tt class="docutils literal"><span class="pre">GetModuleHandleW</span></tt>
explicitly, and then call it with bytes or string objects respectively.</p>
<p>Sometimes, dlls export functions with names which aren&#8217;t valid Python
identifiers, like <tt class="docutils literal"><span class="pre">&quot;??2&#64;YAPAXI&#64;Z&quot;</span></tt>. In this case you have to use
<a class="reference internal" href="functions.html#getattr" title="getattr"><tt class="xref py py-func docutils literal"><span class="pre">getattr()</span></tt></a> to retrieve the function:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span><span class="p">,</span> <span class="s">&quot;??2@YAPAXI@Z&quot;</span><span class="p">)</span> 
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On Windows, some dlls export functions not by name but by ordinal. These
functions can be accessed by indexing the dll object with the ordinal number:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> 
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
  File <span class="nb">&quot;ctypes.py&quot;</span>, line <span class="m">310</span>, in <span class="n-Identifier">__getitem__</span>
    <span class="n">func</span> <span class="o">=</span> <span class="n">_StdcallFuncPtr</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="nc">AttributeError</span>: <span class="n-Identifier">function ordinal 0 not found</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions">
<span id="ctypes-calling-functions"></span><h3>15.17.1.3. Calling functions<a class="headerlink" href="#calling-functions" title="Permalink to this headline">¶</a></h3>
<p>You can call these functions like any other Python callable. This example uses
the <tt class="docutils literal"><span class="pre">time()</span></tt> function, which returns system time in seconds since the Unix
epoch, and the <tt class="docutils literal"><span class="pre">GetModuleHandleA()</span></tt> function, which returns a win32 module
handle.</p>
<p>This example calls both functions with a NULL pointer (<tt class="xref docutils literal"><span class="pre">None</span></tt> should be used
as the NULL pointer):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">libc</span><span class="o">.</span><span class="n">time</span><span class="p">(</span><span class="k">None</span><span class="p">))</span> 
<span class="go">1150640792</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="k">None</span><span class="p">)))</span> 
<span class="go">0x1d000000</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> tries to protect you from calling functions with the wrong number
of arguments or the wrong calling convention.  Unfortunately this only works on
Windows.  It does this by examining the stack after the function returns, so
although an error is raised the function <em>has</em> been called:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">()</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">Procedure probably called with not enough arguments (4 bytes missing)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">Procedure probably called with too many arguments (4 bytes in excess)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The same exception is raised when you call an <tt class="docutils literal"><span class="pre">stdcall</span></tt> function with the
<tt class="docutils literal"><span class="pre">cdecl</span></tt> calling convention, or vice versa:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="k">None</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">Procedure probably called with not enough arguments (4 bytes missing)</span>
<span class="go">&gt;&gt;&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">msvcrt</span><span class="o">.</span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;spam&quot;</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">Procedure probably called with too many arguments (4 bytes in excess)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>To find out the correct calling convention you have to look into the C header
file or the documentation for the function you want to call.</p>
<p>On Windows, <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
argument values:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="mi">32</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">WindowsError: exception</span>: <span class="n-Identifier">access violation reading 0x00000020</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>There are, however, enough ways to crash Python with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>, so you
should be careful anyway.</p>
<p><tt class="xref docutils literal"><span class="pre">None</span></tt>, integers, bytes objects and (unicode) strings are the only native
Python objects that can directly be used as parameters in these function calls.
<tt class="xref docutils literal"><span class="pre">None</span></tt> is passed as a C <tt class="docutils literal"><span class="pre">NULL</span></tt> pointer, bytes objects and strings are passed
as pointer to the memory block that contains their data (<tt class="xref c c-type docutils literal"><span class="pre">char</span> <span class="pre">*</span></tt> or
<tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span> <span class="pre">*</span></tt>).  Python integers are passed as the platforms default C
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> type, their value is masked to fit into the C type.</p>
<p>Before we move on calling functions with other parameter types, we have to learn
more about <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> data types.</p>
</div>
<div class="section" id="fundamental-data-types">
<span id="ctypes-fundamental-data-types"></span><h3>15.17.1.4. Fundamental data types<a class="headerlink" href="#fundamental-data-types" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> defines a number of primitive C compatible data types :</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="46%" />
<col width="30%" />
</colgroup>
<thead valign="bottom">
<tr><th class="head">ctypes type</th>
<th class="head">C type</th>
<th class="head">Python type</th>
</tr>
</thead>
<tbody valign="top">
<tr><td><a class="reference internal" href="#ctypes.c_bool" title="ctypes.c_bool"><tt class="xref py py-class docutils literal"><span class="pre">c_bool</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">_Bool</span></tt></td>
<td>bool (1)</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_char" title="ctypes.c_char"><tt class="xref py py-class docutils literal"><span class="pre">c_char</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">char</span></tt></td>
<td>1-character bytes object</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_wchar" title="ctypes.c_wchar"><tt class="xref py py-class docutils literal"><span class="pre">c_wchar</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span></tt></td>
<td>1-character string</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_byte" title="ctypes.c_byte"><tt class="xref py py-class docutils literal"><span class="pre">c_byte</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">char</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_ubyte" title="ctypes.c_ubyte"><tt class="xref py py-class docutils literal"><span class="pre">c_ubyte</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">char</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_short" title="ctypes.c_short"><tt class="xref py py-class docutils literal"><span class="pre">c_short</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">short</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_ushort" title="ctypes.c_ushort"><tt class="xref py py-class docutils literal"><span class="pre">c_ushort</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">short</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">int</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_uint" title="ctypes.c_uint"><tt class="xref py py-class docutils literal"><span class="pre">c_uint</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><tt class="xref py py-class docutils literal"><span class="pre">c_long</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">long</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_ulong" title="ctypes.c_ulong"><tt class="xref py py-class docutils literal"><span class="pre">c_ulong</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">long</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_longlong" title="ctypes.c_longlong"><tt class="xref py py-class docutils literal"><span class="pre">c_longlong</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">__int64</span></tt> or <tt class="xref c c-type docutils literal"><span class="pre">long</span> <span class="pre">long</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_ulonglong" title="ctypes.c_ulonglong"><tt class="xref py py-class docutils literal"><span class="pre">c_ulonglong</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">__int64</span></tt> or
<tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></tt></td>
<td>int</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_float" title="ctypes.c_float"><tt class="xref py py-class docutils literal"><span class="pre">c_float</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">float</span></tt></td>
<td>float</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_double" title="ctypes.c_double"><tt class="xref py py-class docutils literal"><span class="pre">c_double</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">double</span></tt></td>
<td>float</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_longdouble" title="ctypes.c_longdouble"><tt class="xref py py-class docutils literal"><span class="pre">c_longdouble</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">long</span> <span class="pre">double</span></tt></td>
<td>float</td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><tt class="xref py py-class docutils literal"><span class="pre">c_char_p</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">char</span> <span class="pre">*</span></tt> (NUL terminated)</td>
<td>bytes object or <tt class="xref docutils literal"><span class="pre">None</span></tt></td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_wchar_p" title="ctypes.c_wchar_p"><tt class="xref py py-class docutils literal"><span class="pre">c_wchar_p</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span> <span class="pre">*</span></tt> (NUL terminated)</td>
<td>string or <tt class="xref docutils literal"><span class="pre">None</span></tt></td>
</tr>
<tr><td><a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><tt class="xref py py-class docutils literal"><span class="pre">c_void_p</span></tt></a></td>
<td><tt class="xref c c-type docutils literal"><span class="pre">void</span> <span class="pre">*</span></tt></td>
<td>int or <tt class="xref docutils literal"><span class="pre">None</span></tt></td>
</tr>
</tbody>
</table>
<ol class="arabic simple">
<li>The constructor accepts any object with a truth value.</li>
</ol>
<p>All these types can be created by calling them with an optional initializer of
the correct type and value:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c_int</span><span class="p">()</span>
<span class="go">c_long(0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_wchar_p</span><span class="p">(</span><span class="s">&quot;Hello, World&quot;</span><span class="p">)</span>
<span class="go">c_wchar_p(&#39;Hello, World&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_ushort</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">)</span>
<span class="go">c_ushort(65533)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Since these types are mutable, their value can also be changed afterwards:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="go">c_long(42)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="o">-</span><span class="mi">99</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="go">-99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning a new value to instances of the pointer types <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><tt class="xref py py-class docutils literal"><span class="pre">c_char_p</span></tt></a>,
<a class="reference internal" href="#ctypes.c_wchar_p" title="ctypes.c_wchar_p"><tt class="xref py py-class docutils literal"><span class="pre">c_wchar_p</span></tt></a>, and <a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><tt class="xref py py-class docutils literal"><span class="pre">c_void_p</span></tt></a> changes the <em>memory location</em> they
point to, <em>not the contents</em> of the memory block (of course not, because Python
bytes objects are immutable):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&quot;Hello, World&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_s</span> <span class="o">=</span> <span class="n">c_wchar_p</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">c_s</span><span class="p">)</span>
<span class="go">c_wchar_p(&#39;Hello, World&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_s</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="s">&quot;Hi, there&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">c_s</span><span class="p">)</span>
<span class="go">c_wchar_p(&#39;Hi, there&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>                 <span class="c"># first object is unchanged</span>
<span class="go">Hello, World</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You should be careful, however, not to pass them to functions expecting pointers
to mutable memory. If you need mutable memory blocks, ctypes has a
<a class="reference internal" href="#ctypes.create_string_buffer" title="ctypes.create_string_buffer"><tt class="xref py py-func docutils literal"><span class="pre">create_string_buffer()</span></tt></a> function which creates these in various ways.  The
current memory block contents can be accessed (or changed) with the <tt class="docutils literal"><span class="pre">raw</span></tt>
property; if you want to access it as NUL terminated string, use the <tt class="docutils literal"><span class="pre">value</span></tt>
property:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>            <span class="c"># create a 3 byte buffer, initialized to NUL bytes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">))</span>
<span class="go">3 b&#39;\x00\x00\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;Hello&quot;</span><span class="p">)</span>     <span class="c"># create a buffer containing a NUL terminated string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">))</span>
<span class="go">6 b&#39;Hello\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">value</span><span class="p">))</span>
<span class="go">b&#39;Hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;Hello&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span> <span class="c"># create a 10 byte buffer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">))</span>
<span class="go">10 b&#39;Hello\x00\x00\x00\x00\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">b</span><span class="s">&quot;Hi&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">))</span>
<span class="go">10 b&#39;Hi\x00lo\x00\x00\x00\x00\x00&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#ctypes.create_string_buffer" title="ctypes.create_string_buffer"><tt class="xref py py-func docutils literal"><span class="pre">create_string_buffer()</span></tt></a> function replaces the <tt class="xref py py-func docutils literal"><span class="pre">c_buffer()</span></tt> function
(which is still available as an alias), as well as the <tt class="xref py py-func docutils literal"><span class="pre">c_string()</span></tt> function
from earlier ctypes releases.  To create a mutable memory block containing
unicode characters of the C type <tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span></tt> use the
<a class="reference internal" href="#ctypes.create_unicode_buffer" title="ctypes.create_unicode_buffer"><tt class="xref py py-func docutils literal"><span class="pre">create_unicode_buffer()</span></tt></a> function.</p>
</div>
<div class="section" id="calling-functions-continued">
<span id="ctypes-calling-functions-continued"></span><h3>15.17.1.5. Calling functions, continued<a class="headerlink" href="#calling-functions-continued" title="Permalink to this headline">¶</a></h3>
<p>Note that printf prints to the real standard output channel, <em>not</em> to
<a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><tt class="xref py py-data docutils literal"><span class="pre">sys.stdout</span></tt></a>, so these examples will only work at the console prompt, not
from within <em>IDLE</em> or <em>PythonWin</em>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">printf</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;Hello, %s</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;World!&quot;</span><span class="p">)</span>
<span class="go">Hello, World!</span>
<span class="go">14</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;Hello, %S</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="s">&quot;World!&quot;</span><span class="p">)</span>
<span class="go">Hello, World!</span>
<span class="go">14</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;%d bottles of beer</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="go">42 bottles of beer</span>
<span class="go">19</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;%f bottles of beer</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="mf">42.5</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ArgumentError: argument 2: exceptions.TypeError</span>: <span class="n-Identifier">Don&#39;t know how to convert parameter 2</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>As has been mentioned before, all Python types except integers, strings, and
bytes objects have to be wrapped in their corresponding <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> type, so
that they can be converted to the required C data type:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;An int %d, a double %f</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="mi">1234</span><span class="p">,</span> <span class="n">c_double</span><span class="p">(</span><span class="mf">3.14</span><span class="p">))</span>
<span class="go">An int 1234, a double 3.140000</span>
<span class="go">31</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions-with-your-own-custom-data-types">
<span id="ctypes-calling-functions-with-own-custom-data-types"></span><h3>15.17.1.6. Calling functions with your own custom data types<a class="headerlink" href="#calling-functions-with-your-own-custom-data-types" title="Permalink to this headline">¶</a></h3>
<p>You can also customize <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> argument conversion to allow instances of
your own classes be used as function arguments.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> looks for an
<tt class="xref py py-attr docutils literal"><span class="pre">_as_parameter_</span></tt> attribute and uses this as the function argument.  Of
course, it must be one of integer, string, or bytes:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Bottles</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">_as_parameter_</span> <span class="o">=</span> <span class="n">number</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bottles</span> <span class="o">=</span> <span class="n">Bottles</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;%d bottles of beer</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">bottles</span><span class="p">)</span>
<span class="go">42 bottles of beer</span>
<span class="go">19</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you don&#8217;t want to store the instance&#8217;s data in the <tt class="xref py py-attr docutils literal"><span class="pre">_as_parameter_</span></tt>
instance variable, you could define a <a class="reference internal" href="functions.html#property" title="property"><tt class="xref py py-class docutils literal"><span class="pre">property</span></tt></a> which makes the
attribute available on request.</p>
</div>
<div class="section" id="specifying-the-required-argument-types-function-prototypes">
<span id="ctypes-specifying-required-argument-types"></span><h3>15.17.1.7. Specifying the required argument types (function prototypes)<a class="headerlink" href="#specifying-the-required-argument-types-function-prototypes" title="Permalink to this headline">¶</a></h3>
<p>It is possible to specify the required argument types of functions exported from
DLLs by setting the <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> attribute.</p>
<p><tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> must be a sequence of C data types (the <tt class="docutils literal"><span class="pre">printf</span></tt> function is
probably not a good example here, because it takes a variable number and
different types of parameters depending on the format string, on the other hand
this is quite handy to experiment with this feature):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="o">.</span><span class="n">argtypes</span> <span class="o">=</span> <span class="p">[</span><span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="n">c_double</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;String &#39;%s&#39;, Int %d, Double %f</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;Hi&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mf">2.2</span><span class="p">)</span>
<span class="go">String &#39;Hi&#39;, Int 10, Double 2.200000</span>
<span class="go">37</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Specifying a format protects against incompatible argument types (just as a
prototype for a C function), and tries to convert the arguments to valid types:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;%d %d %d&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ArgumentError: argument 2: exceptions.TypeError</span>: <span class="n-Identifier">wrong type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;%s %d %f</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;X&quot;</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">X 2 3.000000</span>
<span class="go">13</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you have defined your own classes which you pass to function calls, you have
to implement a <tt class="xref py py-meth docutils literal"><span class="pre">from_param()</span></tt> class method for them to be able to use them
in the <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> sequence. The <tt class="xref py py-meth docutils literal"><span class="pre">from_param()</span></tt> class method receives
the Python object passed to the function call, it should do a typecheck or
whatever is needed to make sure this object is acceptable, and then return the
object itself, its <tt class="xref py py-attr docutils literal"><span class="pre">_as_parameter_</span></tt> attribute, or whatever you want to
pass as the C function argument in this case. Again, the result should be an
integer, string, bytes, a <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> instance, or an object with an
<tt class="xref py py-attr docutils literal"><span class="pre">_as_parameter_</span></tt> attribute.</p>
</div>
<div class="section" id="return-types">
<span id="ctypes-return-types"></span><h3>15.17.1.8. Return types<a class="headerlink" href="#return-types" title="Permalink to this headline">¶</a></h3>
<p>By default functions are assumed to return the C <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> type.  Other
return types can be specified by setting the <tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt> attribute of the
function object.</p>
<p>Here is a more advanced example, it uses the <tt class="docutils literal"><span class="pre">strchr</span></tt> function, which expects
a string pointer and a char, and returns a pointer to a string:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">strchr</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s">&quot;d&quot;</span><span class="p">))</span> 
<span class="go">8059983</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">c_char_p</span>   <span class="c"># c_char_p is a pointer to a string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s">&quot;d&quot;</span><span class="p">))</span>
<span class="go">b&#39;def&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s">&quot;x&quot;</span><span class="p">)))</span>
<span class="go">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you want to avoid the <tt class="docutils literal"><span class="pre">ord(&quot;x&quot;)</span></tt> calls above, you can set the
<tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> attribute, and the second argument will be converted from a
single character Python bytes object into a C char:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">c_char_p</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">argtypes</span> <span class="o">=</span> <span class="p">[</span><span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_char</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;d&quot;</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;def&quot;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ArgumentError: argument 2: exceptions.TypeError</span>: <span class="n-Identifier">one character string expected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;x&quot;</span><span class="p">))</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;abcdef&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;d&quot;</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You can also use a callable Python object (a function or a class for example) as
the <tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt> attribute, if the foreign function returns an integer.  The
callable will be called with the <em>integer</em> the C function returns, and the
result of this call will be used as the result of your function call. This is
useful to check for error return values and automatically raise an exception:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span> <span class="o">=</span> <span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span> 
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ValidHandle</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">value</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">ValidHandle</span> 
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="p">(</span><span class="k">None</span><span class="p">)</span> 
<span class="go">486539264</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="p">(</span><span class="s">&quot;something silly&quot;</span><span class="p">)</span> 
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n-Identifier">ValidHandle</span>
<span class="nc">WindowsError</span>: <span class="n-Identifier">[Errno 126] The specified module could not be found.</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">WinError</span></tt> is a function which will call Windows <tt class="docutils literal"><span class="pre">FormatMessage()</span></tt> api to
get the string representation of an error code, and <em>returns</em> an exception.
<tt class="docutils literal"><span class="pre">WinError</span></tt> takes an optional error code parameter, if no one is used, it calls
<a class="reference internal" href="#ctypes.GetLastError" title="ctypes.GetLastError"><tt class="xref py py-func docutils literal"><span class="pre">GetLastError()</span></tt></a> to retrieve it.</p>
<p>Please note that a much more powerful error checking mechanism is available
through the <tt class="xref py py-attr docutils literal"><span class="pre">errcheck</span></tt> attribute; see the reference manual for details.</p>
</div>
<div class="section" id="passing-pointers-or-passing-parameters-by-reference">
<span id="ctypes-passing-pointers"></span><h3>15.17.1.9. Passing pointers (or: passing parameters by reference)<a class="headerlink" href="#passing-pointers-or-passing-parameters-by-reference" title="Permalink to this headline">¶</a></h3>
<p>Sometimes a C api function expects a <em>pointer</em> to a data type as parameter,
probably to write into the corresponding location, or if the data is too large
to be passed by value. This is also known as <em>passing parameters by reference</em>.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> exports the <a class="reference internal" href="#ctypes.byref" title="ctypes.byref"><tt class="xref py py-func docutils literal"><span class="pre">byref()</span></tt></a> function which is used to pass parameters
by reference.  The same effect can be achieved with the <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><tt class="xref py py-func docutils literal"><span class="pre">pointer()</span></tt></a> function,
although <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><tt class="xref py py-func docutils literal"><span class="pre">pointer()</span></tt></a> does a lot more work since it constructs a real pointer
object, so it is faster to use <a class="reference internal" href="#ctypes.byref" title="ctypes.byref"><tt class="xref py py-func docutils literal"><span class="pre">byref()</span></tt></a> if you don&#8217;t need the pointer
object in Python itself:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">c_float</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="n">b</span><span class="s">&#39;</span><span class="se">\000</span><span class="s">&#39;</span> <span class="o">*</span> <span class="mi">32</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">value</span><span class="p">))</span>
<span class="go">0 0.0 b&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">sscanf</span><span class="p">(</span><span class="n">b</span><span class="s">&quot;1 3.14 Hello&quot;</span><span class="p">,</span> <span class="n">b</span><span class="s">&quot;%d %f %s&quot;</span><span class="p">,</span>
<span class="gp">... </span>            <span class="n">byref</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">byref</span><span class="p">(</span><span class="n">f</span><span class="p">),</span> <span class="n">s</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">value</span><span class="p">))</span>
<span class="go">1 3.1400001049 b&#39;Hello&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="structures-and-unions">
<span id="ctypes-structures-unions"></span><h3>15.17.1.10. Structures and unions<a class="headerlink" href="#structures-and-unions" title="Permalink to this headline">¶</a></h3>
<p>Structures and unions must derive from the <a class="reference internal" href="#ctypes.Structure" title="ctypes.Structure"><tt class="xref py py-class docutils literal"><span class="pre">Structure</span></tt></a> and <a class="reference internal" href="#ctypes.Union" title="ctypes.Union"><tt class="xref py py-class docutils literal"><span class="pre">Union</span></tt></a>
base classes which are defined in the <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> module. Each subclass must
define a <tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt> attribute.  <tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt> must be a list of
<em>2-tuples</em>, containing a <em>field name</em> and a <em>field type</em>.</p>
<p>The field type must be a <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> type like <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a>, or any other
derived <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> type: structure, union, array, pointer.</p>
<p>Here is a simple example of a POINT structure, which contains two integers named
<em>x</em> and <em>y</em>, and also shows how to initialize a structure in the constructor:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">10 20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">0 5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">too many initializers</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You can, however, build much more complicated structures. Structures can itself
contain other structures by using a structure as a field type.</p>
<p>Here is a RECT structure which contains two POINTs named <em>upperleft</em> and
<em>lowerright</em>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">RECT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;upperleft&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;lowerright&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">rc</span><span class="o">.</span><span class="n">upperleft</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">upperleft</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">0 5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">rc</span><span class="o">.</span><span class="n">lowerright</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">lowerright</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">0 0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Nested structures can also be initialized in the constructor in several ways:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">((</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
</pre></div>
</div>
<p>Field <a class="reference internal" href="../glossary.html#term-descriptor"><em class="xref std std-term">descriptor</em></a>s can be retrieved from the <em>class</em>, they are useful
for debugging because they can provide useful information:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">POINT</span><span class="o">.</span><span class="n">x</span><span class="p">)</span>
<span class="go">&lt;Field type=c_long, ofs=0, size=4&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">POINT</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">&lt;Field type=c_long, ofs=4, size=4&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="structure-union-alignment-and-byte-order">
<span id="ctypes-structureunion-alignment-byte-order"></span><h3>15.17.1.11. Structure/union alignment and byte order<a class="headerlink" href="#structure-union-alignment-and-byte-order" title="Permalink to this headline">¶</a></h3>
<p>By default, Structure and Union fields are aligned in the same way the C
compiler does it. It is possible to override this behavior be specifying a
<tt class="xref py py-attr docutils literal"><span class="pre">_pack_</span></tt> class attribute in the subclass definition. This must be set to a
positive integer and specifies the maximum alignment for the fields. This is
what <tt class="docutils literal"><span class="pre">#pragma</span> <span class="pre">pack(n)</span></tt> also does in MSVC.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> uses the native byte order for Structures and Unions.  To build
structures with non-native byte order, you can use one of the
<a class="reference internal" href="#ctypes.BigEndianStructure" title="ctypes.BigEndianStructure"><tt class="xref py py-class docutils literal"><span class="pre">BigEndianStructure</span></tt></a>, <a class="reference internal" href="#ctypes.LittleEndianStructure" title="ctypes.LittleEndianStructure"><tt class="xref py py-class docutils literal"><span class="pre">LittleEndianStructure</span></tt></a>,
<tt class="xref py py-class docutils literal"><span class="pre">BigEndianUnion</span></tt>, and <tt class="xref py py-class docutils literal"><span class="pre">LittleEndianUnion</span></tt> base classes.  These
classes cannot contain pointer fields.</p>
</div>
<div class="section" id="bit-fields-in-structures-and-unions">
<span id="ctypes-bit-fields-in-structures-unions"></span><h3>15.17.1.12. Bit fields in structures and unions<a class="headerlink" href="#bit-fields-in-structures-and-unions" title="Permalink to this headline">¶</a></h3>
<p>It is possible to create structures and unions containing bit fields. Bit fields
are only possible for integer fields, the bit width is specified as the third
item in the <tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt> tuples:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Int</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;first_16&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="mi">16</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;second_16&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="mi">16</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">Int</span><span class="o">.</span><span class="n">first_16</span><span class="p">)</span>
<span class="go">&lt;Field type=c_long, ofs=0:0, bits=16&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">Int</span><span class="o">.</span><span class="n">second_16</span><span class="p">)</span>
<span class="go">&lt;Field type=c_long, ofs=0:16, bits=16&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="arrays">
<span id="ctypes-arrays"></span><h3>15.17.1.13. Arrays<a class="headerlink" href="#arrays" title="Permalink to this headline">¶</a></h3>
<p>Arrays are sequences, containing a fixed number of instances of the same type.</p>
<p>The recommended way to create array types is by multiplying a data type with a
positive integer:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">TenPointsArrayType</span> <span class="o">=</span> <span class="n">POINT</span> <span class="o">*</span> <span class="mi">10</span>
</pre></div>
</div>
<p>Here is an example of an somewhat artificial data type, a structure containing 4
POINTs among other stuff:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>   <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyStruct</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>   <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;a&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span>
<span class="gp">... </span>               <span class="p">(</span><span class="s">&quot;b&quot;</span><span class="p">,</span> <span class="n">c_float</span><span class="p">),</span>
<span class="gp">... </span>               <span class="p">(</span><span class="s">&quot;point_array&quot;</span><span class="p">,</span> <span class="n">POINT</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">MyStruct</span><span class="p">()</span><span class="o">.</span><span class="n">point_array</span><span class="p">))</span>
<span class="go">4</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Instances are created in the usual way, by calling the class:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">arr</span> <span class="o">=</span> <span class="n">TenPointsArrayType</span><span class="p">()</span>
<span class="k">for</span> <span class="n">pt</span> <span class="ow">in</span> <span class="n">arr</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">pt</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">pt</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
<p>The above code print a series of <tt class="docutils literal"><span class="pre">0</span> <span class="pre">0</span></tt> lines, because the array contents is
initialized to zeros.</p>
<p>Initializers of the correct type can also be specified:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TenIntegers</span> <span class="o">=</span> <span class="n">c_int</span> <span class="o">*</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ii</span> <span class="o">=</span> <span class="n">TenIntegers</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">ii</span><span class="p">)</span>
<span class="go">&lt;c_long_Array_10 object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ii</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&quot; &quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">1 2 3 4 5 6 7 8 9 10</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="pointers">
<span id="ctypes-pointers"></span><h3>15.17.1.14. Pointers<a class="headerlink" href="#pointers" title="Permalink to this headline">¶</a></h3>
<p>Pointer instances are created by calling the <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><tt class="xref py py-func docutils literal"><span class="pre">pointer()</span></tt></a> function on a
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> type:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Pointer instances have a <tt class="xref py py-attr docutils literal"><span class="pre">contents</span></tt> attribute which returns the object to
which the pointer points, the <tt class="docutils literal"><span class="pre">i</span></tt> object above:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">c_long(42)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> does not have OOR (original object return), it constructs a
new, equivalent object each time you retrieve an attribute:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="ow">is</span> <span class="n">i</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="ow">is</span> <span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning another <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a> instance to the pointer&#8217;s contents attribute
would cause the pointer to point to the memory location where this is stored:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">99</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="o">=</span> <span class="n">i</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">c_long(99)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Pointer instances can also be indexed with integers:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning to an integer index changes the pointed to value:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="go">c_long(99)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">22</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="go">c_long(22)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is also possible to use indexes different from 0, but you must know what
you&#8217;re doing, just as in C: You can access or change arbitrary memory locations.
Generally you only use this feature if you receive a pointer from a C function,
and you <em>know</em> that the pointer actually points to an array instead of a single
item.</p>
<p>Behind the scenes, the <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><tt class="xref py py-func docutils literal"><span class="pre">pointer()</span></tt></a> function does more than simply create
pointer instances, it has to create pointer <em>types</em> first. This is done with the
<a class="reference internal" href="#ctypes.POINTER" title="ctypes.POINTER"><tt class="xref py py-func docutils literal"><span class="pre">POINTER()</span></tt></a> function, which accepts any <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> type, and returns a
new type:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span>
<span class="go">&lt;class &#39;ctypes.LP_c_long&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">expected c_long instead of int</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span><span class="p">(</span><span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">))</span>
<span class="go">&lt;ctypes.LP_c_long object at 0x...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Calling the pointer type without an argument creates a <tt class="docutils literal"><span class="pre">NULL</span></tt> pointer.
<tt class="docutils literal"><span class="pre">NULL</span></tt> pointers have a <tt class="xref docutils literal"><span class="pre">False</span></tt> boolean value:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">bool</span><span class="p">(</span><span class="n">null_ptr</span><span class="p">))</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> checks for <tt class="docutils literal"><span class="pre">NULL</span></tt> when dereferencing pointers (but dereferencing
invalid non-<tt class="docutils literal"><span class="pre">NULL</span></tt> pointers would crash Python):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">....</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">NULL pointer access</span>
<span class="go">&gt;&gt;&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1234</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">....</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">NULL pointer access</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="type-conversions">
<span id="ctypes-type-conversions"></span><h3>15.17.1.15. Type conversions<a class="headerlink" href="#type-conversions" title="Permalink to this headline">¶</a></h3>
<p>Usually, ctypes does strict type checking.  This means, if you have
<tt class="docutils literal"><span class="pre">POINTER(c_int)</span></tt> in the <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> list of a function or as the type of
a member field in a structure definition, only instances of exactly the same
type are accepted.  There are some exceptions to this rule, where ctypes accepts
other objects.  For example, you can pass compatible array instances instead of
pointer types.  So, for <tt class="docutils literal"><span class="pre">POINTER(c_int)</span></tt>, ctypes accepts an array of c_int:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Bar</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;count&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;values&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span> <span class="o">=</span> <span class="n">Bar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_int</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">bar</span><span class="o">.</span><span class="n">count</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">bar</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>To set a POINTER type field to <tt class="docutils literal"><span class="pre">NULL</span></tt>, you can assign <tt class="xref docutils literal"><span class="pre">None</span></tt>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="k">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Sometimes you have instances of incompatible types.  In C, you can cast one type
into another type.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> provides a <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> function which can be
used in the same way.  The <tt class="docutils literal"><span class="pre">Bar</span></tt> structure defined above accepts
<tt class="docutils literal"><span class="pre">POINTER(c_int)</span></tt> pointers or <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a> arrays for its <tt class="docutils literal"><span class="pre">values</span></tt> field,
but not instances of other types:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
<span class="nc">TypeError</span>: <span class="n-Identifier">incompatible types, c_byte_Array_4 instance instead of LP_c_long instance</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For these cases, the <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> function is handy.</p>
<p>The <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> function can be used to cast a ctypes instance into a pointer
to a different ctypes data type.  <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> takes two parameters, a ctypes
object that is or can be converted to a pointer of some kind, and a ctypes
pointer type.  It returns an instance of the second argument, which references
the same memory block as the first argument:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cast</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="go">&lt;ctypes.LP_c_long object at ...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>So, <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><tt class="xref py py-func docutils literal"><span class="pre">cast()</span></tt></a> can be used to assign to the <tt class="docutils literal"><span class="pre">values</span></tt> field of <tt class="docutils literal"><span class="pre">Bar</span></tt> the
structure:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span> <span class="o">=</span> <span class="n">Bar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="n">cast</span><span class="p">((</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)(),</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">bar</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="go">0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="incomplete-types">
<span id="ctypes-incomplete-types"></span><h3>15.17.1.16. Incomplete Types<a class="headerlink" href="#incomplete-types" title="Permalink to this headline">¶</a></h3>
<p><em>Incomplete Types</em> are structures, unions or arrays whose members are not yet
specified. In C, they are specified by forward declarations, which are defined
later:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">struct</span> <span class="n">cell</span><span class="p">;</span> <span class="o">/*</span> <span class="n">forward</span> <span class="n">declaration</span> <span class="o">*/</span>

<span class="n">struct</span> <span class="n">cell</span> <span class="p">{</span>
    <span class="n">char</span> <span class="o">*</span><span class="n">name</span><span class="p">;</span>
    <span class="n">struct</span> <span class="n">cell</span> <span class="o">*</span><span class="nb">next</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
</div>
<p>The straightforward translation into ctypes code would be this, but it does not
work:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">cell</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;next&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">cell</span><span class="p">))]</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n-Identifier">?</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n-Identifier">cell</span>
<span class="nc">NameError</span>: <span class="n-Identifier">name &#39;cell&#39; is not defined</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>because the new <tt class="docutils literal"><span class="pre">class</span> <span class="pre">cell</span></tt> is not available in the class statement itself.
In <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>, we can define the <tt class="docutils literal"><span class="pre">cell</span></tt> class and set the <tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt>
attribute later, after the class statement:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">cell</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                 <span class="p">(</span><span class="s">&quot;next&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">cell</span><span class="p">))]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Lets try it. We create two instances of <tt class="docutils literal"><span class="pre">cell</span></tt>, and let them point to each
other, and finally follow the pointer chain a few times:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span> <span class="o">=</span> <span class="n">cell</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">&quot;foo&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span> <span class="o">=</span> <span class="n">cell</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">&quot;bar&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">c2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">c1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">c1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&quot; &quot;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">p</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">next</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">foo bar foo bar foo bar foo bar</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-functions">
<span id="ctypes-callback-functions"></span><h3>15.17.1.17. Callback functions<a class="headerlink" href="#callback-functions" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> allows to create C callable function pointers from Python callables.
These are sometimes called <em>callback functions</em>.</p>
<p>First, you must create a class for the callback function, the class knows the
calling convention, the return type, and the number and types of arguments this
function will receive.</p>
<p>The CFUNCTYPE factory function creates types for callback functions using the
normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
function creates types for callback functions using the stdcall calling
convention.</p>
<p>Both of these factory functions are called with the result type as first
argument, and the callback functions expected argument types as the remaining
arguments.</p>
<p>I will present an example here which uses the standard C library&#8217;s
<tt class="xref c c-func docutils literal"><span class="pre">qsort()</span></tt> function, this is used to sort items with the help of a callback
function.  <tt class="xref c c-func docutils literal"><span class="pre">qsort()</span></tt> will be used to sort an array of integers:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">IntArray5</span> <span class="o">=</span> <span class="n">c_int</span> <span class="o">*</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ia</span> <span class="o">=</span> <span class="n">IntArray5</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">33</span><span class="p">,</span> <span class="mi">99</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">qsort</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="k">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><tt class="xref py py-func docutils literal"><span class="pre">qsort()</span></tt> must be called with a pointer to the data to sort, the number of
items in the data array, the size of one item, and a pointer to the comparison
function, the callback. The callback will then be called with two pointers to
items, and it must return a negative integer if the first item is smaller than
the second, a zero if they are equal, and a positive integer else.</p>
<p>So our callback function receives pointers to integers, and must return an
integer. First we create the <tt class="docutils literal"><span class="pre">type</span></tt> for the callback function:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">CMPFUNC</span> <span class="o">=</span> <span class="n">CFUNCTYPE</span><span class="p">(</span><span class="n">c_int</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For the first implementation of the callback function, we simply print the
arguments we get, and return 0 (incremental development ;-):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="mi">0</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Create the C callable callback:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">cmp_func</span> <span class="o">=</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>And we&#8217;re ready to go:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span> 
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>We know how to access the contents of a pointer, so lets redefine our callback:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cmp_func</span> <span class="o">=</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Here is what we get on Windows:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span> 
<span class="go">py_cmp_func 7 1</span>
<span class="go">py_cmp_func 33 1</span>
<span class="go">py_cmp_func 99 1</span>
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 7 5</span>
<span class="go">py_cmp_func 33 5</span>
<span class="go">py_cmp_func 99 5</span>
<span class="go">py_cmp_func 7 99</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is funny to see that on linux the sort function seems to work much more
efficiently, it is doing less comparisons:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span> 
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Ah, we&#8217;re nearly done! The last step is to actually compare the two items and
return a useful result:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Final run on Windows:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">))</span> 
<span class="go">py_cmp_func 33 7</span>
<span class="go">py_cmp_func 99 33</span>
<span class="go">py_cmp_func 5 99</span>
<span class="go">py_cmp_func 1 99</span>
<span class="go">py_cmp_func 33 7</span>
<span class="go">py_cmp_func 1 33</span>
<span class="go">py_cmp_func 5 33</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">py_cmp_func 5 1</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>and on Linux:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">))</span> 
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is quite interesting to see that the Windows <tt class="xref py py-func docutils literal"><span class="pre">qsort()</span></tt> function needs
more comparisons than the linux version!</p>
<p>As we can easily check, our array is sorted now:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ia</span><span class="p">:</span> <span class="nb">print</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s">&quot; &quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">1 5 7 33 99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><strong>Important note for callback functions:</strong></p>
<p>Make sure you keep references to CFUNCTYPE objects as long as they are used from
C code. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> doesn&#8217;t, and if you don&#8217;t, they may be garbage collected,
crashing your program when a callback is made.</p>
</div>
<div class="section" id="accessing-values-exported-from-dlls">
<span id="ctypes-accessing-values-exported-from-dlls"></span><h3>15.17.1.18. Accessing values exported from dlls<a class="headerlink" href="#accessing-values-exported-from-dlls" title="Permalink to this headline">¶</a></h3>
<p>Some shared libraries not only export functions, they also export variables. An
example in the Python library itself is the <tt class="xref c c-data docutils literal"><span class="pre">Py_OptimizeFlag</span></tt>, an integer
set to 0, 1, or 2, depending on the <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><em class="xref std std-option">-O</em></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-OO"><em class="xref std std-option">-OO</em></a> flag given on
startup.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> can access values like this with the <tt class="xref py py-meth docutils literal"><span class="pre">in_dll()</span></tt> class methods of
the type.  <em>pythonapi</em> is a predefined symbol giving access to the Python C
api:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">opt_flag</span> <span class="o">=</span> <span class="n">c_int</span><span class="o">.</span><span class="n">in_dll</span><span class="p">(</span><span class="n">pythonapi</span><span class="p">,</span> <span class="s">&quot;Py_OptimizeFlag&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">opt_flag</span><span class="p">)</span>
<span class="go">c_long(0)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If the interpreter would have been started with <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><em class="xref std std-option">-O</em></a>, the sample would
have printed <tt class="docutils literal"><span class="pre">c_long(1)</span></tt>, or <tt class="docutils literal"><span class="pre">c_long(2)</span></tt> if <a class="reference internal" href="../using/cmdline.html#cmdoption-OO"><em class="xref std std-option">-OO</em></a> would have been
specified.</p>
<p>An extended example which also demonstrates the use of pointers accesses the
<a class="reference internal" href="../c-api/import.html#PyImport_FrozenModules" title="PyImport_FrozenModules"><tt class="xref c c-data docutils literal"><span class="pre">PyImport_FrozenModules</span></tt></a> pointer exported by Python.</p>
<p>Quoting the docs for that value:</p>
<blockquote>
<div>This pointer is initialized to point to an array of <tt class="xref c c-type docutils literal"><span class="pre">struct</span> <span class="pre">_frozen</span></tt>
records, terminated by one whose members are all <em>NULL</em> or zero.  When a frozen
module is imported, it is searched in this table.  Third-party code could play
tricks with this to provide a dynamically created collection of frozen modules.</div></blockquote>
<p>So manipulating this pointer could even prove useful. To restrict the example
size, we show only how this table can be read with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">struct_frozen</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;code&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_ubyte</span><span class="p">)),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s">&quot;size&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>We have defined the <tt class="xref c c-type docutils literal"><span class="pre">struct</span> <span class="pre">_frozen</span></tt> data type, so we can get the pointer
to the table:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">FrozenTable</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">struct_frozen</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="n">FrozenTable</span><span class="o">.</span><span class="n">in_dll</span><span class="p">(</span><span class="n">pythonapi</span><span class="p">,</span> <span class="s">&quot;PyImport_FrozenModules&quot;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Since <tt class="docutils literal"><span class="pre">table</span></tt> is a <tt class="docutils literal"><span class="pre">pointer</span></tt> to the array of <tt class="docutils literal"><span class="pre">struct_frozen</span></tt> records, we
can iterate over it, but we just have to make sure that our loop terminates,
because pointers have no size. Sooner or later it would probably crash with an
access violation or whatever, so it&#8217;s better to break out of the loop when we
hit the NULL entry:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">table</span><span class="p">:</span>
<span class="gp">... </span>   <span class="nb">print</span><span class="p">(</span><span class="n">item</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">item</span><span class="o">.</span><span class="n">size</span><span class="p">)</span>
<span class="gp">... </span>   <span class="k">if</span> <span class="n">item</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="k">None</span><span class="p">:</span>
<span class="gp">... </span>       <span class="k">break</span>
<span class="gp">...</span>
<span class="go">__hello__ 104</span>
<span class="go">__phello__ -104</span>
<span class="go">__phello__.spam 104</span>
<span class="go">None 0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The fact that standard Python has a frozen module and a frozen package
(indicated by the negative size member) is not well known, it is only used for
testing. Try it out with <tt class="docutils literal"><span class="pre">import</span> <span class="pre">__hello__</span></tt> for example.</p>
</div>
<div class="section" id="surprises">
<span id="ctypes-surprises"></span><h3>15.17.1.19. Surprises<a class="headerlink" href="#surprises" title="Permalink to this headline">¶</a></h3>
<p>There are some edges in <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> where you may be expect something else than
what actually happens.</p>
<p>Consider the following example:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">RECT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;a&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">),</span> <span class="p">(</span><span class="s">&quot;b&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">1 2 3 4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># now swap the two points</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>
<span class="go">3 4 3 4</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Hm. We certainly expected the last statement to print <tt class="docutils literal"><span class="pre">3</span> <span class="pre">4</span> <span class="pre">1</span> <span class="pre">2</span></tt>. What
happened? Here are the steps of the <tt class="docutils literal"><span class="pre">rc.a,</span> <span class="pre">rc.b</span> <span class="pre">=</span> <span class="pre">rc.b,</span> <span class="pre">rc.a</span></tt> line above:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">temp0</span><span class="p">,</span> <span class="n">temp1</span> <span class="o">=</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="n">temp0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">temp1</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that <tt class="docutils literal"><span class="pre">temp0</span></tt> and <tt class="docutils literal"><span class="pre">temp1</span></tt> are objects still using the internal buffer of
the <tt class="docutils literal"><span class="pre">rc</span></tt> object above. So executing <tt class="docutils literal"><span class="pre">rc.a</span> <span class="pre">=</span> <span class="pre">temp0</span></tt> copies the buffer
contents of <tt class="docutils literal"><span class="pre">temp0</span></tt> into <tt class="docutils literal"><span class="pre">rc</span></tt> &#8216;s buffer.  This, in turn, changes the
contents of <tt class="docutils literal"><span class="pre">temp1</span></tt>. So, the last assignment <tt class="docutils literal"><span class="pre">rc.b</span> <span class="pre">=</span> <span class="pre">temp1</span></tt>, doesn&#8217;t have
the expected effect.</p>
<p>Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
doesn&#8217;t <em>copy</em> the sub-object, instead it retrieves a wrapper object accessing
the root-object&#8217;s underlying buffer.</p>
<p>Another example that may behave different from what one would expect is this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">c_char_p</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="s">&quot;abc def ghi&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;abc def ghi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span> <span class="ow">is</span> <span class="n">s</span><span class="o">.</span><span class="n">value</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Why is it printing <tt class="xref docutils literal"><span class="pre">False</span></tt>?  ctypes instances are objects containing a memory
block plus some <a class="reference internal" href="../glossary.html#term-descriptor"><em class="xref std std-term">descriptor</em></a>s accessing the contents of the memory.
Storing a Python object in the memory block does not store the object itself,
instead the <tt class="docutils literal"><span class="pre">contents</span></tt> of the object is stored.  Accessing the contents again
constructs a new Python object each time!</p>
</div>
<div class="section" id="variable-sized-data-types">
<span id="ctypes-variable-sized-data-types"></span><h3>15.17.1.20. Variable-sized data types<a class="headerlink" href="#variable-sized-data-types" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> provides some support for variable-sized arrays and structures.</p>
<p>The <a class="reference internal" href="#ctypes.resize" title="ctypes.resize"><tt class="xref py py-func docutils literal"><span class="pre">resize()</span></tt></a> function can be used to resize the memory buffer of an
existing ctypes object.  The function takes the object as first argument, and
the requested size in bytes as the second argument.  The memory block cannot be
made smaller than the natural memory block specified by the objects type, a
<a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised if this is tried:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_short</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">sizeof</span><span class="p">(</span><span class="n">short_array</span><span class="p">))</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resize</span><span class="p">(</span><span class="n">short_array</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="nc">ValueError</span>: <span class="n-Identifier">minimum size is 8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resize</span><span class="p">(</span><span class="n">short_array</span><span class="p">,</span> <span class="mi">32</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sizeof</span><span class="p">(</span><span class="n">short_array</span><span class="p">)</span>
<span class="go">32</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sizeof</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">short_array</span><span class="p">))</span>
<span class="go">8</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>This is nice and fine, but how would one access the additional elements
contained in this array?  Since the type still only knows about 4 elements, we
get errors accessing other elements:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span><span class="p">[:]</span>
<span class="go">[0, 0, 0, 0]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span><span class="p">[</span><span class="mi">7</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="nc">IndexError</span>: <span class="n-Identifier">invalid index</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Another way to use variable-sized data types with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> is to use the
dynamic nature of Python, and (re-)define the data type after the required size
is already known, on a case by case basis.</p>
</div>
</div>
<div class="section" id="ctypes-reference">
<span id="ctypes-ctypes-reference"></span><h2>15.17.2. ctypes reference<a class="headerlink" href="#ctypes-reference" title="Permalink to this headline">¶</a></h2>
<div class="section" id="finding-shared-libraries">
<span id="ctypes-finding-shared-libraries"></span><h3>15.17.2.1. Finding shared libraries<a class="headerlink" href="#finding-shared-libraries" title="Permalink to this headline">¶</a></h3>
<p>When programming in a compiled language, shared libraries are accessed when
compiling/linking a program, and when the program is run.</p>
<p>The purpose of the <tt class="xref py py-func docutils literal"><span class="pre">find_library()</span></tt> function is to locate a library in a way
similar to what the compiler does (on platforms with several versions of a
shared library the most recent should be loaded), while the ctypes library
loaders act like when a program is run, and call the runtime loader directly.</p>
<p>The <tt class="xref py py-mod docutils literal"><span class="pre">ctypes.util</span></tt> module provides a function which can help to determine
the library to load.</p>
<dl class="data">
<dt>
<tt class="descclassname">ctypes.util.</tt><tt class="descname">find_library</tt><big>(</big><em>name</em><big>)</big></dt>
<dd><p>Try to find a library and return a pathname.  <em>name</em> is the library name without
any prefix like <em>lib</em>, suffix like <tt class="docutils literal"><span class="pre">.so</span></tt>, <tt class="docutils literal"><span class="pre">.dylib</span></tt> or version number (this
is the form used for the posix linker option <em class="xref std std-option">-l</em>).  If no library can
be found, returns <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
</dd></dl>

<p>The exact functionality is system dependent.</p>
<p>On Linux, <tt class="xref py py-func docutils literal"><span class="pre">find_library()</span></tt> tries to run external programs
(<tt class="docutils literal"><span class="pre">/sbin/ldconfig</span></tt>, <tt class="docutils literal"><span class="pre">gcc</span></tt>, and <tt class="docutils literal"><span class="pre">objdump</span></tt>) to find the library file.  It
returns the filename of the library file.  Here are some examples:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.util</span> <span class="k">import</span> <span class="n">find_library</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;m&quot;</span><span class="p">)</span>
<span class="go">&#39;libm.so.6&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;c&quot;</span><span class="p">)</span>
<span class="go">&#39;libc.so.6&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;bz2&quot;</span><span class="p">)</span>
<span class="go">&#39;libbz2.so.1.0&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On OS X, <tt class="xref py py-func docutils literal"><span class="pre">find_library()</span></tt> tries several predefined naming schemes and paths
to locate the library, and returns a full pathname if successful:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.util</span> <span class="k">import</span> <span class="n">find_library</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;c&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libc.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;m&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libm.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;bz2&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libbz2.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s">&quot;AGL&quot;</span><span class="p">)</span>
<span class="go">&#39;/System/Library/Frameworks/AGL.framework/AGL&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On Windows, <tt class="xref py py-func docutils literal"><span class="pre">find_library()</span></tt> searches along the system search path, and
returns the full pathname, but since there is no predefined naming scheme a call
like <tt class="docutils literal"><span class="pre">find_library(&quot;c&quot;)</span></tt> will fail and return <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p>If wrapping a shared library with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>, it <em>may</em> be better to determine
the shared library name at development type, and hardcode that into the wrapper
module instead of using <tt class="xref py py-func docutils literal"><span class="pre">find_library()</span></tt> to locate the library at runtime.</p>
</div>
<div class="section" id="loading-shared-libraries">
<span id="ctypes-loading-shared-libraries"></span><h3>15.17.2.2. Loading shared libraries<a class="headerlink" href="#loading-shared-libraries" title="Permalink to this headline">¶</a></h3>
<p>There are several ways to loaded shared libraries into the Python process.  One
way is to instantiate one of the following classes:</p>
<dl class="class">
<dt id="ctypes.CDLL">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">CDLL</tt><big>(</big><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><big>)</big><a class="headerlink" href="#ctypes.CDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class represent loaded shared libraries. Functions in these
libraries use the standard C calling convention, and are assumed to return
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.OleDLL">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">OleDLL</tt><big>(</big><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><big>)</big><a class="headerlink" href="#ctypes.OleDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Instances of this class represent loaded shared libraries,
functions in these libraries use the <tt class="docutils literal"><span class="pre">stdcall</span></tt> calling convention, and are
assumed to return the windows specific <a class="reference internal" href="#ctypes.HRESULT" title="ctypes.HRESULT"><tt class="xref py py-class docutils literal"><span class="pre">HRESULT</span></tt></a> code.  <a class="reference internal" href="#ctypes.HRESULT" title="ctypes.HRESULT"><tt class="xref py py-class docutils literal"><span class="pre">HRESULT</span></tt></a>
values contain information specifying whether the function call failed or
succeeded, together with additional error code.  If the return value signals a
failure, an <a class="reference internal" href="exceptions.html#WindowsError" title="WindowsError"><tt class="xref py py-class docutils literal"><span class="pre">WindowsError</span></tt></a> is automatically raised.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.WinDLL">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">WinDLL</tt><big>(</big><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><big>)</big><a class="headerlink" href="#ctypes.WinDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Instances of this class represent loaded shared libraries,
functions in these libraries use the <tt class="docutils literal"><span class="pre">stdcall</span></tt> calling convention, and are
assumed to return <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt> by default.</p>
<p>On Windows CE only the standard calling convention is used, for convenience the
<a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><tt class="xref py py-class docutils literal"><span class="pre">WinDLL</span></tt></a> and <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><tt class="xref py py-class docutils literal"><span class="pre">OleDLL</span></tt></a> use the standard calling convention on this
platform.</p>
</dd></dl>

<p>The Python <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><em class="xref std std-term">global interpreter lock</em></a> is released before calling any
function exported by these libraries, and reacquired afterwards.</p>
<dl class="class">
<dt id="ctypes.PyDLL">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">PyDLL</tt><big>(</big><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em><big>)</big><a class="headerlink" href="#ctypes.PyDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class behave like <a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><tt class="xref py py-class docutils literal"><span class="pre">CDLL</span></tt></a> instances, except that the
Python GIL is <em>not</em> released during the function call, and after the function
execution the Python error flag is checked. If the error flag is set, a Python
exception is raised.</p>
<p>Thus, this is only useful to call Python C api functions directly.</p>
</dd></dl>

<p>All these classes can be instantiated by calling them with at least one
argument, the pathname of the shared library.  If you have an existing handle to
an already loaded shared library, it can be passed as the <tt class="docutils literal"><span class="pre">handle</span></tt> named
parameter, otherwise the underlying platforms <tt class="docutils literal"><span class="pre">dlopen</span></tt> or <tt class="docutils literal"><span class="pre">LoadLibrary</span></tt>
function is used to load the library into the process, and to get a handle to
it.</p>
<p>The <em>mode</em> parameter can be used to specify how the library is loaded.  For
details, consult the <em class="manpage">dlopen(3)</em> manpage, on Windows, <em>mode</em> is
ignored.</p>
<p>The <em>use_errno</em> parameter, when set to True, enables a ctypes mechanism that
allows to access the system <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a> error number in a safe way.
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> maintains a thread-local copy of the systems <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a>
variable; if you call foreign functions created with <tt class="docutils literal"><span class="pre">use_errno=True</span></tt> then the
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a> value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.</p>
<p>The function <a class="reference internal" href="#ctypes.get_errno" title="ctypes.get_errno"><tt class="xref py py-func docutils literal"><span class="pre">ctypes.get_errno()</span></tt></a> returns the value of the ctypes private
copy, and the function <a class="reference internal" href="#ctypes.set_errno" title="ctypes.set_errno"><tt class="xref py py-func docutils literal"><span class="pre">ctypes.set_errno()</span></tt></a> changes the ctypes private copy
to a new value and returns the former value.</p>
<p>The <em>use_last_error</em> parameter, when set to True, enables the same mechanism for
the Windows error code which is managed by the <a class="reference internal" href="#ctypes.GetLastError" title="ctypes.GetLastError"><tt class="xref py py-func docutils literal"><span class="pre">GetLastError()</span></tt></a> and
<tt class="xref py py-func docutils literal"><span class="pre">SetLastError()</span></tt> Windows API functions; <a class="reference internal" href="#ctypes.get_last_error" title="ctypes.get_last_error"><tt class="xref py py-func docutils literal"><span class="pre">ctypes.get_last_error()</span></tt></a> and
<a class="reference internal" href="#ctypes.set_last_error" title="ctypes.set_last_error"><tt class="xref py py-func docutils literal"><span class="pre">ctypes.set_last_error()</span></tt></a> are used to request and change the ctypes private
copy of the windows error code.</p>
<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">RTLD_GLOBAL</tt></dt>
<dd><p>Flag to use as <em>mode</em> parameter.  On platforms where this flag is not available,
it is defined as the integer zero.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">RTLD_LOCAL</tt></dt>
<dd><p>Flag to use as <em>mode</em> parameter.  On platforms where this is not available, it
is the same as <em>RTLD_GLOBAL</em>.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">DEFAULT_MODE</tt></dt>
<dd><p>The default mode which is used to load shared libraries.  On OSX 10.3, this is
<em>RTLD_GLOBAL</em>, otherwise it is the same as <em>RTLD_LOCAL</em>.</p>
</dd></dl>

<p>Instances of these classes have no public methods, however <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a>
and <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> have special behavior: functions exported by the shared
library can be accessed as attributes of by index.  Please note that both
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> and <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><tt class="xref py py-meth docutils literal"><span class="pre">__getitem__()</span></tt></a> cache their result, so calling them
repeatedly returns the same object each time.</p>
<p>The following public attributes are available, their name starts with an
underscore to not clash with exported function names:</p>
<dl class="attribute">
<dt id="ctypes.PyDLL._handle">
<tt class="descclassname">PyDLL.</tt><tt class="descname">_handle</tt><a class="headerlink" href="#ctypes.PyDLL._handle" title="Permalink to this definition">¶</a></dt>
<dd><p>The system handle used to access the library.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.PyDLL._name">
<tt class="descclassname">PyDLL.</tt><tt class="descname">_name</tt><a class="headerlink" href="#ctypes.PyDLL._name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the library passed in the constructor.</p>
</dd></dl>

<p>Shared libraries can also be loaded by using one of the prefabricated objects,
which are instances of the <a class="reference internal" href="#ctypes.LibraryLoader" title="ctypes.LibraryLoader"><tt class="xref py py-class docutils literal"><span class="pre">LibraryLoader</span></tt></a> class, either by calling the
<tt class="xref py py-meth docutils literal"><span class="pre">LoadLibrary()</span></tt> method, or by retrieving the library as attribute of the
loader instance.</p>
<dl class="class">
<dt id="ctypes.LibraryLoader">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">LibraryLoader</tt><big>(</big><em>dlltype</em><big>)</big><a class="headerlink" href="#ctypes.LibraryLoader" title="Permalink to this definition">¶</a></dt>
<dd><p>Class which loads shared libraries.  <em>dlltype</em> should be one of the
<a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><tt class="xref py py-class docutils literal"><span class="pre">CDLL</span></tt></a>, <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><tt class="xref py py-class docutils literal"><span class="pre">PyDLL</span></tt></a>, <a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><tt class="xref py py-class docutils literal"><span class="pre">WinDLL</span></tt></a>, or <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><tt class="xref py py-class docutils literal"><span class="pre">OleDLL</span></tt></a> types.</p>
<p><a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><tt class="xref py py-meth docutils literal"><span class="pre">__getattr__()</span></tt></a> has special behavior: It allows to load a shared library by
accessing it as attribute of a library loader instance.  The result is cached,
so repeated attribute accesses return the same library each time.</p>
<dl class="method">
<dt id="ctypes.LibraryLoader.LoadLibrary">
<tt class="descname">LoadLibrary</tt><big>(</big><em>name</em><big>)</big><a class="headerlink" href="#ctypes.LibraryLoader.LoadLibrary" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a shared library into the process and return it.  This method always
returns a new instance of the library.</p>
</dd></dl>

</dd></dl>

<p>These prefabricated library loaders are available:</p>
<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">cdll</tt></dt>
<dd><p>Creates <a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><tt class="xref py py-class docutils literal"><span class="pre">CDLL</span></tt></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">windll</tt></dt>
<dd><p>Windows only: Creates <a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><tt class="xref py py-class docutils literal"><span class="pre">WinDLL</span></tt></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">oledll</tt></dt>
<dd><p>Windows only: Creates <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><tt class="xref py py-class docutils literal"><span class="pre">OleDLL</span></tt></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">pydll</tt></dt>
<dd><p>Creates <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><tt class="xref py py-class docutils literal"><span class="pre">PyDLL</span></tt></a> instances.</p>
</dd></dl>

<p>For accessing the C Python api directly, a ready-to-use Python shared library
object is available:</p>
<dl class="data">
<dt>
<tt class="descclassname">ctypes.</tt><tt class="descname">pythonapi</tt></dt>
<dd><p>An instance of <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><tt class="xref py py-class docutils literal"><span class="pre">PyDLL</span></tt></a> that exposes Python C API functions as
attributes.  Note that all these functions are assumed to return C
<tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>, which is of course not always the truth, so you have to assign
the correct <tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt> attribute to use these functions.</p>
</dd></dl>

</div>
<div class="section" id="foreign-functions">
<span id="ctypes-foreign-functions"></span><h3>15.17.2.3. Foreign functions<a class="headerlink" href="#foreign-functions" title="Permalink to this headline">¶</a></h3>
<p>As explained in the previous section, foreign functions can be accessed as
attributes of loaded shared libraries.  The function objects created in this way
by default accept any number of arguments, accept any ctypes data instances as
arguments, and return the default result type specified by the library loader.
They are instances of a private class:</p>
<dl class="class">
<dt id="ctypes._FuncPtr">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">_FuncPtr</tt><a class="headerlink" href="#ctypes._FuncPtr" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for C callable foreign functions.</p>
<p>Instances of foreign functions are also C compatible data types; they
represent C function pointers.</p>
<p>This behavior can be customized by assigning to special attributes of the
foreign function object.</p>
<dl class="attribute">
<dt id="ctypes._FuncPtr.restype">
<tt class="descname">restype</tt><a class="headerlink" href="#ctypes._FuncPtr.restype" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a ctypes type to specify the result type of the foreign function.
Use <tt class="xref docutils literal"><span class="pre">None</span></tt> for <tt class="xref c c-type docutils literal"><span class="pre">void</span></tt>, a function not returning anything.</p>
<p>It is possible to assign a callable Python object that is not a ctypes
type, in this case the function is assumed to return a C <tt class="xref c c-type docutils literal"><span class="pre">int</span></tt>, and
the callable will be called with this integer, allowing to do further
processing or error checking.  Using this is deprecated, for more flexible
post processing or error checking use a ctypes data type as
<a class="reference internal" href="#ctypes._FuncPtr.restype" title="ctypes._FuncPtr.restype"><tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt></a> and assign a callable to the <a class="reference internal" href="#ctypes._FuncPtr.errcheck" title="ctypes._FuncPtr.errcheck"><tt class="xref py py-attr docutils literal"><span class="pre">errcheck</span></tt></a> attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._FuncPtr.argtypes">
<tt class="descname">argtypes</tt><a class="headerlink" href="#ctypes._FuncPtr.argtypes" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a tuple of ctypes types to specify the argument types that the
function accepts.  Functions using the <tt class="docutils literal"><span class="pre">stdcall</span></tt> calling convention can
only be called with the same number of arguments as the length of this
tuple; functions using the C calling convention accept additional,
unspecified arguments as well.</p>
<p>When a foreign function is called, each actual argument is passed to the
<tt class="xref py py-meth docutils literal"><span class="pre">from_param()</span></tt> class method of the items in the <a class="reference internal" href="#ctypes._FuncPtr.argtypes" title="ctypes._FuncPtr.argtypes"><tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt></a>
tuple, this method allows to adapt the actual argument to an object that
the foreign function accepts.  For example, a <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><tt class="xref py py-class docutils literal"><span class="pre">c_char_p</span></tt></a> item in
the <a class="reference internal" href="#ctypes._FuncPtr.argtypes" title="ctypes._FuncPtr.argtypes"><tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt></a> tuple will convert a string passed as argument into
a bytes object using ctypes conversion rules.</p>
<p>New: It is now possible to put items in argtypes which are not ctypes
types, but each item must have a <tt class="xref py py-meth docutils literal"><span class="pre">from_param()</span></tt> method which returns a
value usable as argument (integer, string, ctypes instance).  This allows
to define adapters that can adapt custom objects as function parameters.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._FuncPtr.errcheck">
<tt class="descname">errcheck</tt><a class="headerlink" href="#ctypes._FuncPtr.errcheck" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a Python function or another callable to this attribute. The
callable will be called with three or more arguments:</p>
<dl class="function">
<dt>
<tt class="descname">callable</tt><big>(</big><em>result</em>, <em>func</em>, <em>arguments</em><big>)</big></dt>
<dd><p><em>result</em> is what the foreign function returns, as specified by the
<a class="reference internal" href="#ctypes._FuncPtr.restype" title="ctypes._FuncPtr.restype"><tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt></a> attribute.</p>
<p><em>func</em> is the foreign function object itself, this allows to reuse the
same callable object to check or post process the results of several
functions.</p>
<p><em>arguments</em> is a tuple containing the parameters originally passed to
the function call, this allows to specialize the behavior on the
arguments used.</p>
</dd></dl>

<p>The object that this function returns will be returned from the
foreign function call, but it can also check the result value
and raise an exception if the foreign function call failed.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="ctypes.ArgumentError">
<em class="property">exception </em><tt class="descclassname">ctypes.</tt><tt class="descname">ArgumentError</tt><a class="headerlink" href="#ctypes.ArgumentError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a foreign function call cannot convert one of the
passed arguments.</p>
</dd></dl>

</div>
<div class="section" id="function-prototypes">
<span id="ctypes-function-prototypes"></span><h3>15.17.2.4. Function prototypes<a class="headerlink" href="#function-prototypes" title="Permalink to this headline">¶</a></h3>
<p>Foreign functions can also be created by instantiating function prototypes.
Function prototypes are similar to function prototypes in C; they describe a
function (return type, argument types, calling convention) without defining an
implementation.  The factory functions must be called with the desired result
type and the argument types of the function.</p>
<dl class="function">
<dt id="ctypes.CFUNCTYPE">
<tt class="descclassname">ctypes.</tt><tt class="descname">CFUNCTYPE</tt><big>(</big><em>restype</em>, <em>*argtypes</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><big>)</big><a class="headerlink" href="#ctypes.CFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>The returned function prototype creates functions that use the standard C
calling convention.  The function will release the GIL during the call.  If
<em>use_errno</em> is set to True, the ctypes private copy of the system
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a> variable is exchanged with the real <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a> value before
and after the call; <em>use_last_error</em> does the same for the Windows error
code.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.WINFUNCTYPE">
<tt class="descclassname">ctypes.</tt><tt class="descname">WINFUNCTYPE</tt><big>(</big><em>restype</em>, <em>*argtypes</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><big>)</big><a class="headerlink" href="#ctypes.WINFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: The returned function prototype creates functions that use the
<tt class="docutils literal"><span class="pre">stdcall</span></tt> calling convention, except on Windows CE where
<a class="reference internal" href="#ctypes.WINFUNCTYPE" title="ctypes.WINFUNCTYPE"><tt class="xref py py-func docutils literal"><span class="pre">WINFUNCTYPE()</span></tt></a> is the same as <a class="reference internal" href="#ctypes.CFUNCTYPE" title="ctypes.CFUNCTYPE"><tt class="xref py py-func docutils literal"><span class="pre">CFUNCTYPE()</span></tt></a>.  The function will
release the GIL during the call.  <em>use_errno</em> and <em>use_last_error</em> have the
same meaning as above.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.PYFUNCTYPE">
<tt class="descclassname">ctypes.</tt><tt class="descname">PYFUNCTYPE</tt><big>(</big><em>restype</em>, <em>*argtypes</em><big>)</big><a class="headerlink" href="#ctypes.PYFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>The returned function prototype creates functions that use the Python calling
convention.  The function will <em>not</em> release the GIL during the call.</p>
</dd></dl>

<p>Function prototypes created by these factory functions can be instantiated in
different ways, depending on the type and number of the parameters in the call:</p>
<blockquote>
<div><dl class="function">
<dt>
<tt class="descname">prototype</tt><big>(</big><em>address</em><big>)</big></dt>
<dd><p>Returns a foreign function at the specified address which must be an integer.</p>
</dd></dl>

<dl class="function">
<dt>
<tt class="descname">prototype</tt><big>(</big><em>callable</em><big>)</big></dt>
<dd><p>Create a C callable function (a callback function) from a Python <em>callable</em>.</p>
</dd></dl>

<dl class="function">
<dt>
<tt class="descname">prototype</tt><big>(</big><em>func_spec</em><span class="optional">[</span>, <em>paramflags</em><span class="optional">]</span><big>)</big></dt>
<dd><p>Returns a foreign function exported by a shared library. <em>func_spec</em> must
be a 2-tuple <tt class="docutils literal"><span class="pre">(name_or_ordinal,</span> <span class="pre">library)</span></tt>. The first item is the name of
the exported function as string, or the ordinal of the exported function
as small integer.  The second item is the shared library instance.</p>
</dd></dl>

<dl class="function">
<dt>
<tt class="descname">prototype</tt><big>(</big><em>vtbl_index</em>, <em>name</em><span class="optional">[</span>, <em>paramflags</em><span class="optional">[</span>, <em>iid</em><span class="optional">]</span><span class="optional">]</span><big>)</big></dt>
<dd><p>Returns a foreign function that will call a COM method. <em>vtbl_index</em> is
the index into the virtual function table, a small non-negative
integer. <em>name</em> is name of the COM method. <em>iid</em> is an optional pointer to
the interface identifier which is used in extended error reporting.</p>
<p>COM methods use a special calling convention: They require a pointer to
the COM interface as first argument, in addition to those parameters that
are specified in the <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> tuple.</p>
</dd></dl>

<p>The optional <em>paramflags</em> parameter creates foreign function wrappers with much
more functionality than the features described above.</p>
<p><em>paramflags</em> must be a tuple of the same length as <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt>.</p>
<p>Each item in this tuple contains further information about a parameter, it must
be a tuple containing one, two, or three items.</p>
<p>The first item is an integer containing a combination of direction
flags for the parameter:</p>
<blockquote>
<div><dl class="docutils">
<dt>1</dt>
<dd>Specifies an input parameter to the function.</dd>
<dt>2</dt>
<dd>Output parameter.  The foreign function fills in a value.</dd>
<dt>4</dt>
<dd>Input parameter which defaults to the integer zero.</dd>
</dl>
</div></blockquote>
<p>The optional second item is the parameter name as string.  If this is specified,
the foreign function can be called with named parameters.</p>
<p>The optional third item is the default value for this parameter.</p>
</div></blockquote>
<p>This example demonstrates how to wrap the Windows <tt class="docutils literal"><span class="pre">MessageBoxA</span></tt> function so
that it supports default parameters and named arguments. The C declaration from
the windows header file is this:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">WINUSERAPI</span> <span class="nb">int</span> <span class="n">WINAPI</span>
<span class="n">MessageBoxA</span><span class="p">(</span>
    <span class="n">HWND</span> <span class="n">hWnd</span> <span class="p">,</span>
    <span class="n">LPCSTR</span> <span class="n">lpText</span><span class="p">,</span>
    <span class="n">LPCSTR</span> <span class="n">lpCaption</span><span class="p">,</span>
    <span class="n">UINT</span> <span class="n">uType</span><span class="p">);</span>
</pre></div>
</div>
<p>Here is the wrapping with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">c_int</span><span class="p">,</span> <span class="n">WINFUNCTYPE</span><span class="p">,</span> <span class="n">windll</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.wintypes</span> <span class="k">import</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">UINT</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prototype</span> <span class="o">=</span> <span class="n">WINFUNCTYPE</span><span class="p">(</span><span class="n">c_int</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">UINT</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paramflags</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">&quot;hwnd&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">&quot;text&quot;</span><span class="p">,</span> <span class="s">&quot;Hi&quot;</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">&quot;caption&quot;</span><span class="p">,</span> <span class="k">None</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">&quot;flags&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span> <span class="o">=</span> <span class="n">prototype</span><span class="p">((</span><span class="s">&quot;MessageBoxA&quot;</span><span class="p">,</span> <span class="n">windll</span><span class="o">.</span><span class="n">user32</span><span class="p">),</span> <span class="n">paramflags</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The MessageBox foreign function can now be called in these ways:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s">&quot;Spam, spam, spam&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">(</span><span class="n">flags</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">text</span><span class="o">=</span><span class="s">&quot;foo bar&quot;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>A second example demonstrates output parameters.  The win32 <tt class="docutils literal"><span class="pre">GetWindowRect</span></tt>
function retrieves the dimensions of a specified window by copying them into
<tt class="docutils literal"><span class="pre">RECT</span></tt> structure that the caller has to supply.  Here is the C declaration:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">WINUSERAPI</span> <span class="n">BOOL</span> <span class="n">WINAPI</span>
<span class="n">GetWindowRect</span><span class="p">(</span>
     <span class="n">HWND</span> <span class="n">hWnd</span><span class="p">,</span>
     <span class="n">LPRECT</span> <span class="n">lpRect</span><span class="p">);</span>
</pre></div>
</div>
<p>Here is the wrapping with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a>:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">POINTER</span><span class="p">,</span> <span class="n">WINFUNCTYPE</span><span class="p">,</span> <span class="n">windll</span><span class="p">,</span> <span class="n">WinError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.wintypes</span> <span class="k">import</span> <span class="n">BOOL</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">RECT</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prototype</span> <span class="o">=</span> <span class="n">WINFUNCTYPE</span><span class="p">(</span><span class="n">BOOL</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">RECT</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paramflags</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s">&quot;hwnd&quot;</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s">&quot;lprect&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span> <span class="o">=</span> <span class="n">prototype</span><span class="p">((</span><span class="s">&quot;GetWindowRect&quot;</span><span class="p">,</span> <span class="n">windll</span><span class="o">.</span><span class="n">user32</span><span class="p">),</span> <span class="n">paramflags</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Functions with output parameters will automatically return the output parameter
value if there is a single one, or a tuple containing the output parameter
values when there are more than one, so the GetWindowRect function now returns a
RECT instance, when called.</p>
<p>Output parameters can be combined with the <tt class="xref py py-attr docutils literal"><span class="pre">errcheck</span></tt> protocol to do
further output processing and error checking.  The win32 <tt class="docutils literal"><span class="pre">GetWindowRect</span></tt> api
function returns a <tt class="docutils literal"><span class="pre">BOOL</span></tt> to signal success or failure, so this function could
do the error checking, and raises an exception when the api call failed:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">errcheck</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">result</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">args</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span><span class="o">.</span><span class="n">errcheck</span> <span class="o">=</span> <span class="n">errcheck</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If the <tt class="xref py py-attr docutils literal"><span class="pre">errcheck</span></tt> function returns the argument tuple it receives
unchanged, <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> continues the normal processing it does on the output
parameters.  If you want to return a tuple of window coordinates instead of a
<tt class="docutils literal"><span class="pre">RECT</span></tt> instance, you can retrieve the fields in the function and return them
instead, the normal processing will no longer take place:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">errcheck</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">result</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">rc</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">rc</span><span class="o">.</span><span class="n">left</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">top</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">bottom</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">right</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span><span class="o">.</span><span class="n">errcheck</span> <span class="o">=</span> <span class="n">errcheck</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="utility-functions">
<span id="ctypes-utility-functions"></span><h3>15.17.2.5. Utility functions<a class="headerlink" href="#utility-functions" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="ctypes.addressof">
<tt class="descclassname">ctypes.</tt><tt class="descname">addressof</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#ctypes.addressof" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the address of the memory buffer as integer.  <em>obj</em> must be an
instance of a ctypes type.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.alignment">
<tt class="descclassname">ctypes.</tt><tt class="descname">alignment</tt><big>(</big><em>obj_or_type</em><big>)</big><a class="headerlink" href="#ctypes.alignment" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the alignment requirements of a ctypes type. <em>obj_or_type</em> must be a
ctypes type or instance.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.byref">
<tt class="descclassname">ctypes.</tt><tt class="descname">byref</tt><big>(</big><em>obj</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#ctypes.byref" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a light-weight pointer to <em>obj</em>, which must be an instance of a
ctypes type.  <em>offset</em> defaults to zero, and must be an integer that will be
added to the internal pointer value.</p>
<p><tt class="docutils literal"><span class="pre">byref(obj,</span> <span class="pre">offset)</span></tt> corresponds to this C code:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="p">(((</span><span class="n">char</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">obj</span><span class="p">)</span> <span class="o">+</span> <span class="n">offset</span><span class="p">)</span>
</pre></div>
</div>
<p>The returned object can only be used as a foreign function call parameter.
It behaves similar to <tt class="docutils literal"><span class="pre">pointer(obj)</span></tt>, but the construction is a lot faster.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.cast">
<tt class="descclassname">ctypes.</tt><tt class="descname">cast</tt><big>(</big><em>obj</em>, <em>type</em><big>)</big><a class="headerlink" href="#ctypes.cast" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to the cast operator in C. It returns a new instance
of <em>type</em> which points to the same memory block as <em>obj</em>.  <em>type</em> must be a
pointer type, and <em>obj</em> must be an object that can be interpreted as a
pointer.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.create_string_buffer">
<tt class="descclassname">ctypes.</tt><tt class="descname">create_string_buffer</tt><big>(</big><em>init_or_size</em>, <em>size=None</em><big>)</big><a class="headerlink" href="#ctypes.create_string_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a mutable character buffer. The returned object is a
ctypes array of <a class="reference internal" href="#ctypes.c_char" title="ctypes.c_char"><tt class="xref py py-class docutils literal"><span class="pre">c_char</span></tt></a>.</p>
<p><em>init_or_size</em> must be an integer which specifies the size of the array, or a
bytes object which will be used to initialize the array items.</p>
<p>If a bytes object is specified as first argument, the buffer is made one item
larger than its length so that the last element in the array is a NUL
termination character. An integer can be passed as second argument which allows
to specify the size of the array if the length of the bytes should not be used.</p>
<p>If the first parameter is a string, it is converted into a bytes object
according to ctypes conversion rules.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.create_unicode_buffer">
<tt class="descclassname">ctypes.</tt><tt class="descname">create_unicode_buffer</tt><big>(</big><em>init_or_size</em>, <em>size=None</em><big>)</big><a class="headerlink" href="#ctypes.create_unicode_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a mutable unicode character buffer. The returned object is
a ctypes array of <a class="reference internal" href="#ctypes.c_wchar" title="ctypes.c_wchar"><tt class="xref py py-class docutils literal"><span class="pre">c_wchar</span></tt></a>.</p>
<p><em>init_or_size</em> must be an integer which specifies the size of the array, or a
string which will be used to initialize the array items.</p>
<p>If a string is specified as first argument, the buffer is made one item
larger than the length of the string so that the last element in the array is a
NUL termination character. An integer can be passed as second argument which
allows to specify the size of the array if the length of the string should not
be used.</p>
<p>If the first parameter is a bytes object, it is converted into an unicode string
according to ctypes conversion rules.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.DllCanUnloadNow">
<tt class="descclassname">ctypes.</tt><tt class="descname">DllCanUnloadNow</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.DllCanUnloadNow" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: This function is a hook which allows to implement in-process
COM servers with ctypes.  It is called from the DllCanUnloadNow function that
the _ctypes extension dll exports.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.DllGetClassObject">
<tt class="descclassname">ctypes.</tt><tt class="descname">DllGetClassObject</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.DllGetClassObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: This function is a hook which allows to implement in-process
COM servers with ctypes.  It is called from the DllGetClassObject function
that the <tt class="docutils literal"><span class="pre">_ctypes</span></tt> extension dll exports.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.util.find_library">
<tt class="descclassname">ctypes.util.</tt><tt class="descname">find_library</tt><big>(</big><em>name</em><big>)</big><a class="headerlink" href="#ctypes.util.find_library" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to find a library and return a pathname.  <em>name</em> is the library name
without any prefix like <tt class="docutils literal"><span class="pre">lib</span></tt>, suffix like <tt class="docutils literal"><span class="pre">.so</span></tt>, <tt class="docutils literal"><span class="pre">.dylib</span></tt> or version
number (this is the form used for the posix linker option <em class="xref std std-option">-l</em>).  If
no library can be found, returns <tt class="xref docutils literal"><span class="pre">None</span></tt>.</p>
<p>The exact functionality is system dependent.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.util.find_msvcrt">
<tt class="descclassname">ctypes.util.</tt><tt class="descname">find_msvcrt</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.util.find_msvcrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: return the filename of the VC runtype library used by Python,
and by the extension modules.  If the name of the library cannot be
determined, <tt class="xref docutils literal"><span class="pre">None</span></tt> is returned.</p>
<p>If you need to free memory, for example, allocated by an extension module
with a call to the <tt class="docutils literal"><span class="pre">free(void</span> <span class="pre">*)</span></tt>, it is important that you use the
function in the same library that allocated the memory.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.FormatError">
<tt class="descclassname">ctypes.</tt><tt class="descname">FormatError</tt><big>(</big><span class="optional">[</span><em>code</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#ctypes.FormatError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Returns a textual description of the error code <em>code</em>.  If no
error code is specified, the last error code is used by calling the Windows
api function GetLastError.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.GetLastError">
<tt class="descclassname">ctypes.</tt><tt class="descname">GetLastError</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.GetLastError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Returns the last error code set by Windows in the calling thread.
This function calls the Windows <cite>GetLastError()</cite> function directly,
it does not return the ctypes-private copy of the error code.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.get_errno">
<tt class="descclassname">ctypes.</tt><tt class="descname">get_errno</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.get_errno" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current value of the ctypes-private copy of the system
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a> variable in the calling thread.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.get_last_error">
<tt class="descclassname">ctypes.</tt><tt class="descname">get_last_error</tt><big>(</big><big>)</big><a class="headerlink" href="#ctypes.get_last_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: returns the current value of the ctypes-private copy of the system
<tt class="xref py py-data docutils literal"><span class="pre">LastError</span></tt> variable in the calling thread.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.memmove">
<tt class="descclassname">ctypes.</tt><tt class="descname">memmove</tt><big>(</big><em>dst</em>, <em>src</em>, <em>count</em><big>)</big><a class="headerlink" href="#ctypes.memmove" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as the standard C memmove library function: copies <em>count</em> bytes from
<em>src</em> to <em>dst</em>. <em>dst</em> and <em>src</em> must be integers or ctypes instances that can
be converted to pointers.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.memset">
<tt class="descclassname">ctypes.</tt><tt class="descname">memset</tt><big>(</big><em>dst</em>, <em>c</em>, <em>count</em><big>)</big><a class="headerlink" href="#ctypes.memset" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as the standard C memset library function: fills the memory block at
address <em>dst</em> with <em>count</em> bytes of value <em>c</em>. <em>dst</em> must be an integer
specifying an address, or a ctypes instance.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.POINTER">
<tt class="descclassname">ctypes.</tt><tt class="descname">POINTER</tt><big>(</big><em>type</em><big>)</big><a class="headerlink" href="#ctypes.POINTER" title="Permalink to this definition">¶</a></dt>
<dd><p>This factory function creates and returns a new ctypes pointer type. Pointer
types are cached an reused internally, so calling this function repeatedly is
cheap. <em>type</em> must be a ctypes type.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.pointer">
<tt class="descclassname">ctypes.</tt><tt class="descname">pointer</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#ctypes.pointer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a new pointer instance, pointing to <em>obj</em>. The returned
object is of the type <tt class="docutils literal"><span class="pre">POINTER(type(obj))</span></tt>.</p>
<p>Note: If you just want to pass a pointer to an object to a foreign function
call, you should use <tt class="docutils literal"><span class="pre">byref(obj)</span></tt> which is much faster.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.resize">
<tt class="descclassname">ctypes.</tt><tt class="descname">resize</tt><big>(</big><em>obj</em>, <em>size</em><big>)</big><a class="headerlink" href="#ctypes.resize" title="Permalink to this definition">¶</a></dt>
<dd><p>This function resizes the internal memory buffer of <em>obj</em>, which must be an
instance of a ctypes type.  It is not possible to make the buffer smaller
than the native size of the objects type, as given by <tt class="docutils literal"><span class="pre">sizeof(type(obj))</span></tt>,
but it is possible to enlarge the buffer.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.set_errno">
<tt class="descclassname">ctypes.</tt><tt class="descname">set_errno</tt><big>(</big><em>value</em><big>)</big><a class="headerlink" href="#ctypes.set_errno" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current value of the ctypes-private copy of the system <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><tt class="xref py py-data docutils literal"><span class="pre">errno</span></tt></a>
variable in the calling thread to <em>value</em> and return the previous value.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.set_last_error">
<tt class="descclassname">ctypes.</tt><tt class="descname">set_last_error</tt><big>(</big><em>value</em><big>)</big><a class="headerlink" href="#ctypes.set_last_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: set the current value of the ctypes-private copy of the system
<tt class="xref py py-data docutils literal"><span class="pre">LastError</span></tt> variable in the calling thread to <em>value</em> and return the
previous value.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.sizeof">
<tt class="descclassname">ctypes.</tt><tt class="descname">sizeof</tt><big>(</big><em>obj_or_type</em><big>)</big><a class="headerlink" href="#ctypes.sizeof" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the size in bytes of a ctypes type or instance memory buffer. Does the
same as the C <tt class="docutils literal"><span class="pre">sizeof()</span></tt> function.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.string_at">
<tt class="descclassname">ctypes.</tt><tt class="descname">string_at</tt><big>(</big><em>address</em>, <em>size=-1</em><big>)</big><a class="headerlink" href="#ctypes.string_at" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns the C string starting at memory address address as a bytes
object. If size is specified, it is used as size, otherwise the string is assumed
to be zero-terminated.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.WinError">
<tt class="descclassname">ctypes.</tt><tt class="descname">WinError</tt><big>(</big><em>code=None</em>, <em>descr=None</em><big>)</big><a class="headerlink" href="#ctypes.WinError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: this function is probably the worst-named thing in ctypes. It
creates an instance of WindowsError.  If <em>code</em> is not specified,
<tt class="docutils literal"><span class="pre">GetLastError</span></tt> is called to determine the error code. If <em>descr</em> is not
specified, <a class="reference internal" href="#ctypes.FormatError" title="ctypes.FormatError"><tt class="xref py py-func docutils literal"><span class="pre">FormatError()</span></tt></a> is called to get a textual description of the
error.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.wstring_at">
<tt class="descclassname">ctypes.</tt><tt class="descname">wstring_at</tt><big>(</big><em>address</em>, <em>size=-1</em><big>)</big><a class="headerlink" href="#ctypes.wstring_at" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns the wide character string starting at memory address
<em>address</em> as a string.  If <em>size</em> is specified, it is used as the number of
characters of the string, otherwise the string is assumed to be
zero-terminated.</p>
</dd></dl>

</div>
<div class="section" id="data-types">
<span id="ctypes-data-types"></span><h3>15.17.2.6. Data types<a class="headerlink" href="#data-types" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes._CData">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">_CData</tt><a class="headerlink" href="#ctypes._CData" title="Permalink to this definition">¶</a></dt>
<dd><p>This non-public class is the common base class of all ctypes data types.
Among other things, all ctypes type instances contain a memory block that
hold C compatible data; the address of the memory block is returned by the
<a class="reference internal" href="#ctypes.addressof" title="ctypes.addressof"><tt class="xref py py-func docutils literal"><span class="pre">addressof()</span></tt></a> helper function. Another instance variable is exposed as
<a class="reference internal" href="#ctypes._CData._objects" title="ctypes._CData._objects"><tt class="xref py py-attr docutils literal"><span class="pre">_objects</span></tt></a>; this contains other Python objects that need to be kept
alive in case the memory block contains pointers.</p>
<p>Common methods of ctypes data types, these are all class methods (to be
exact, they are methods of the <a class="reference internal" href="../glossary.html#term-metaclass"><em class="xref std std-term">metaclass</em></a>):</p>
<dl class="method">
<dt id="ctypes._CData.from_buffer">
<tt class="descname">from_buffer</tt><big>(</big><em>source</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#ctypes._CData.from_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes instance that shares the buffer of the
<em>source</em> object.  The <em>source</em> object must support the writeable buffer
interface.  The optional <em>offset</em> parameter specifies an offset into the
source buffer in bytes; the default is zero.  If the source buffer is not
large enough a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_buffer_copy">
<tt class="descname">from_buffer_copy</tt><big>(</big><em>source</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#ctypes._CData.from_buffer_copy" title="Permalink to this definition">¶</a></dt>
<dd><p>This method creates a ctypes instance, copying the buffer from the
<em>source</em> object buffer which must be readable.  The optional <em>offset</em>
parameter specifies an offset into the source buffer in bytes; the default
is zero.  If the source buffer is not large enough a <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><tt class="xref py py-exc docutils literal"><span class="pre">ValueError</span></tt></a> is
raised.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_address">
<tt class="descname">from_address</tt><big>(</big><em>address</em><big>)</big><a class="headerlink" href="#ctypes._CData.from_address" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes type instance using the memory specified by
<em>address</em> which must be an integer.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_param">
<tt class="descname">from_param</tt><big>(</big><em>obj</em><big>)</big><a class="headerlink" href="#ctypes._CData.from_param" title="Permalink to this definition">¶</a></dt>
<dd><p>This method adapts <em>obj</em> to a ctypes type.  It is called with the actual
object used in a foreign function call when the type is present in the
foreign function&#8217;s <tt class="xref py py-attr docutils literal"><span class="pre">argtypes</span></tt> tuple; it must return an object that
can be used as a function call parameter.</p>
<p>All ctypes data types have a default implementation of this classmethod
that normally returns <em>obj</em> if that is an instance of the type.  Some
types accept other objects as well.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.in_dll">
<tt class="descname">in_dll</tt><big>(</big><em>library</em>, <em>name</em><big>)</big><a class="headerlink" href="#ctypes._CData.in_dll" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes type instance exported by a shared
library. <em>name</em> is the name of the symbol that exports the data, <em>library</em>
is the loaded shared library.</p>
</dd></dl>

<p>Common instance variables of ctypes data types:</p>
<dl class="attribute">
<dt id="ctypes._CData._b_base_">
<tt class="descname">_b_base_</tt><a class="headerlink" href="#ctypes._CData._b_base_" title="Permalink to this definition">¶</a></dt>
<dd><p>Sometimes ctypes data instances do not own the memory block they contain,
instead they share part of the memory block of a base object.  The
<a class="reference internal" href="#ctypes._CData._b_base_" title="ctypes._CData._b_base_"><tt class="xref py py-attr docutils literal"><span class="pre">_b_base_</span></tt></a> read-only member is the root ctypes object that owns the
memory block.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._CData._b_needsfree_">
<tt class="descname">_b_needsfree_</tt><a class="headerlink" href="#ctypes._CData._b_needsfree_" title="Permalink to this definition">¶</a></dt>
<dd><p>This read-only variable is true when the ctypes data instance has
allocated the memory block itself, false otherwise.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._CData._objects">
<tt class="descname">_objects</tt><a class="headerlink" href="#ctypes._CData._objects" title="Permalink to this definition">¶</a></dt>
<dd><p>This member is either <tt class="xref docutils literal"><span class="pre">None</span></tt> or a dictionary containing Python objects
that need to be kept alive so that the memory block contents is kept
valid.  This object is only exposed for debugging; never modify the
contents of this dictionary.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="ctypes-fundamental-data-types-2">
<span id="id1"></span><h3>15.17.2.7. Fundamental data types<a class="headerlink" href="#ctypes-fundamental-data-types-2" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes._SimpleCData">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">_SimpleCData</tt><a class="headerlink" href="#ctypes._SimpleCData" title="Permalink to this definition">¶</a></dt>
<dd><p>This non-public class is the base class of all fundamental ctypes data
types. It is mentioned here because it contains the common attributes of the
fundamental ctypes data types.  <a class="reference internal" href="#ctypes._SimpleCData" title="ctypes._SimpleCData"><tt class="xref py py-class docutils literal"><span class="pre">_SimpleCData</span></tt></a> is a subclass of
<a class="reference internal" href="#ctypes._CData" title="ctypes._CData"><tt class="xref py py-class docutils literal"><span class="pre">_CData</span></tt></a>, so it inherits their methods and attributes. ctypes data
types that are not and do not contain pointers can now be pickled.</p>
<p>Instances have a single attribute:</p>
<dl class="attribute">
<dt id="ctypes._SimpleCData.value">
<tt class="descname">value</tt><a class="headerlink" href="#ctypes._SimpleCData.value" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute contains the actual value of the instance. For integer and
pointer types, it is an integer, for character types, it is a single
character bytes object or string, for character pointer types it is a
Python bytes object or string.</p>
<p>When the <tt class="docutils literal"><span class="pre">value</span></tt> attribute is retrieved from a ctypes instance, usually
a new object is returned each time.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> does <em>not</em> implement
original object return, always a new object is constructed.  The same is
true for all other ctypes object instances.</p>
</dd></dl>

</dd></dl>

<p>Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently
converted to native Python types.  In other words, if a foreign function has a
<tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt> of <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><tt class="xref py py-class docutils literal"><span class="pre">c_char_p</span></tt></a>, you will always receive a Python bytes
object, <em>not</em> a <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><tt class="xref py py-class docutils literal"><span class="pre">c_char_p</span></tt></a> instance.</p>
<p>Subclasses of fundamental data types do <em>not</em> inherit this behavior. So, if a
foreign functions <tt class="xref py py-attr docutils literal"><span class="pre">restype</span></tt> is a subclass of <a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><tt class="xref py py-class docutils literal"><span class="pre">c_void_p</span></tt></a>, you will
receive an instance of this subclass from the function call. Of course, you can
get the value of the pointer by accessing the <tt class="docutils literal"><span class="pre">value</span></tt> attribute.</p>
<p>These are the fundamental ctypes data types:</p>
<dl class="class">
<dt id="ctypes.c_byte">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_byte</tt><a class="headerlink" href="#ctypes.c_byte" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">char</span></tt> datatype, and interprets the value as
small integer.  The constructor accepts an optional integer initializer; no
overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_char">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_char</tt><a class="headerlink" href="#ctypes.c_char" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">char</span></tt> datatype, and interprets the value as a single
character.  The constructor accepts an optional string initializer, the
length of the string must be exactly one character.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_char_p">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_char_p</tt><a class="headerlink" href="#ctypes.c_char_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">char</span> <span class="pre">*</span></tt> datatype when it points to a zero-terminated
string.  For a general character pointer that may also point to binary data,
<tt class="docutils literal"><span class="pre">POINTER(c_char)</span></tt> must be used.  The constructor accepts an integer
address, or a bytes object.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_double">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_double</tt><a class="headerlink" href="#ctypes.c_double" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">double</span></tt> datatype.  The constructor accepts an
optional float initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_longdouble">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_longdouble</tt><a class="headerlink" href="#ctypes.c_longdouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">long</span> <span class="pre">double</span></tt> datatype.  The constructor accepts an
optional float initializer.  On platforms where <tt class="docutils literal"><span class="pre">sizeof(long</span> <span class="pre">double)</span> <span class="pre">==</span>
<span class="pre">sizeof(double)</span></tt> it is an alias to <a class="reference internal" href="#ctypes.c_double" title="ctypes.c_double"><tt class="xref py py-class docutils literal"><span class="pre">c_double</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_float">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_float</tt><a class="headerlink" href="#ctypes.c_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">float</span></tt> datatype.  The constructor accepts an
optional float initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_int</tt><a class="headerlink" href="#ctypes.c_int" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">int</span></tt> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.  On platforms
where <tt class="docutils literal"><span class="pre">sizeof(int)</span> <span class="pre">==</span> <span class="pre">sizeof(long)</span></tt> it is an alias to <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><tt class="xref py py-class docutils literal"><span class="pre">c_long</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int8">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_int8</tt><a class="headerlink" href="#ctypes.c_int8" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 8-bit <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_byte" title="ctypes.c_byte"><tt class="xref py py-class docutils literal"><span class="pre">c_byte</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int16">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_int16</tt><a class="headerlink" href="#ctypes.c_int16" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 16-bit <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_short" title="ctypes.c_short"><tt class="xref py py-class docutils literal"><span class="pre">c_short</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int32">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_int32</tt><a class="headerlink" href="#ctypes.c_int32" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 32-bit <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int64">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_int64</tt><a class="headerlink" href="#ctypes.c_int64" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 64-bit <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_longlong" title="ctypes.c_longlong"><tt class="xref py py-class docutils literal"><span class="pre">c_longlong</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_long">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_long</tt><a class="headerlink" href="#ctypes.c_long" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">long</span></tt> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_longlong">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_longlong</tt><a class="headerlink" href="#ctypes.c_longlong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">long</span> <span class="pre">long</span></tt> datatype.  The constructor accepts
an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_short">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_short</tt><a class="headerlink" href="#ctypes.c_short" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">signed</span> <span class="pre">short</span></tt> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_size_t">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_size_t</tt><a class="headerlink" href="#ctypes.c_size_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">size_t</span></tt> datatype.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ssize_t">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_ssize_t</tt><a class="headerlink" href="#ctypes.c_ssize_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">ssize_t</span></tt> datatype.</p>
<p class="versionadded">
<span class="versionmodified">New in version 3.2.</span></p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ubyte">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_ubyte</tt><a class="headerlink" href="#ctypes.c_ubyte" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">char</span></tt> datatype, it interprets the value as
small integer.  The constructor accepts an optional integer initializer; no
overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_uint</tt><a class="headerlink" href="#ctypes.c_uint" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.  On platforms
where <tt class="docutils literal"><span class="pre">sizeof(int)</span> <span class="pre">==</span> <span class="pre">sizeof(long)</span></tt> it is an alias for <a class="reference internal" href="#ctypes.c_ulong" title="ctypes.c_ulong"><tt class="xref py py-class docutils literal"><span class="pre">c_ulong</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint8">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_uint8</tt><a class="headerlink" href="#ctypes.c_uint8" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 8-bit <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ubyte" title="ctypes.c_ubyte"><tt class="xref py py-class docutils literal"><span class="pre">c_ubyte</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint16">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_uint16</tt><a class="headerlink" href="#ctypes.c_uint16" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 16-bit <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ushort" title="ctypes.c_ushort"><tt class="xref py py-class docutils literal"><span class="pre">c_ushort</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint32">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_uint32</tt><a class="headerlink" href="#ctypes.c_uint32" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 32-bit <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_uint" title="ctypes.c_uint"><tt class="xref py py-class docutils literal"><span class="pre">c_uint</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint64">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_uint64</tt><a class="headerlink" href="#ctypes.c_uint64" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 64-bit <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">int</span></tt> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ulonglong" title="ctypes.c_ulonglong"><tt class="xref py py-class docutils literal"><span class="pre">c_ulonglong</span></tt></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ulong">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_ulong</tt><a class="headerlink" href="#ctypes.c_ulong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">long</span></tt> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ulonglong">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_ulonglong</tt><a class="headerlink" href="#ctypes.c_ulonglong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></tt> datatype.  The constructor
accepts an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ushort">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_ushort</tt><a class="headerlink" href="#ctypes.c_ushort" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">unsigned</span> <span class="pre">short</span></tt> datatype.  The constructor accepts
an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_void_p">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_void_p</tt><a class="headerlink" href="#ctypes.c_void_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">void</span> <span class="pre">*</span></tt> type.  The value is represented as integer.
The constructor accepts an optional integer initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_wchar">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_wchar</tt><a class="headerlink" href="#ctypes.c_wchar" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span></tt> datatype, and interprets the value as a
single character unicode string.  The constructor accepts an optional string
initializer, the length of the string must be exactly one character.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_wchar_p">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_wchar_p</tt><a class="headerlink" href="#ctypes.c_wchar_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <tt class="xref c c-type docutils literal"><span class="pre">wchar_t</span> <span class="pre">*</span></tt> datatype, which must be a pointer to a
zero-terminated wide character string.  The constructor accepts an integer
address, or a string.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_bool">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">c_bool</tt><a class="headerlink" href="#ctypes.c_bool" title="Permalink to this definition">¶</a></dt>
<dd><p>Represent the C <tt class="xref c c-type docutils literal"><span class="pre">bool</span></tt> datatype (more accurately, <tt class="xref c c-type docutils literal"><span class="pre">_Bool</span></tt> from
C99).  Its value can be True or False, and the constructor accepts any object
that has a truth value.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.HRESULT">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">HRESULT</tt><a class="headerlink" href="#ctypes.HRESULT" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Represents a <tt class="xref c c-type docutils literal"><span class="pre">HRESULT</span></tt> value, which contains success or
error information for a function or method call.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.py_object">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">py_object</tt><a class="headerlink" href="#ctypes.py_object" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <a class="reference internal" href="../c-api/structures.html#PyObject" title="PyObject"><tt class="xref c c-type docutils literal"><span class="pre">PyObject</span> <span class="pre">*</span></tt></a> datatype.  Calling this without an
argument creates a <tt class="docutils literal"><span class="pre">NULL</span></tt> <a class="reference internal" href="../c-api/structures.html#PyObject" title="PyObject"><tt class="xref c c-type docutils literal"><span class="pre">PyObject</span> <span class="pre">*</span></tt></a> pointer.</p>
</dd></dl>

<p>The <tt class="xref py py-mod docutils literal"><span class="pre">ctypes.wintypes</span></tt> module provides quite some other Windows specific
data types, for example <tt class="xref c c-type docutils literal"><span class="pre">HWND</span></tt>, <tt class="xref c c-type docutils literal"><span class="pre">WPARAM</span></tt>, or <tt class="xref c c-type docutils literal"><span class="pre">DWORD</span></tt>.  Some
useful structures like <tt class="xref c c-type docutils literal"><span class="pre">MSG</span></tt> or <tt class="xref c c-type docutils literal"><span class="pre">RECT</span></tt> are also defined.</p>
</div>
<div class="section" id="structured-data-types">
<span id="ctypes-structured-data-types"></span><h3>15.17.2.8. Structured data types<a class="headerlink" href="#structured-data-types" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes.Union">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">Union</tt><big>(</big><em>*args</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#ctypes.Union" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for unions in native byte order.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.BigEndianStructure">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">BigEndianStructure</tt><big>(</big><em>*args</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#ctypes.BigEndianStructure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>big endian</em> byte order.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.LittleEndianStructure">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">LittleEndianStructure</tt><big>(</big><em>*args</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#ctypes.LittleEndianStructure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>little endian</em> byte order.</p>
</dd></dl>

<p>Structures with non-native byte order cannot contain pointer type fields, or any
other data types containing pointer type fields.</p>
<dl class="class">
<dt id="ctypes.Structure">
<em class="property">class </em><tt class="descclassname">ctypes.</tt><tt class="descname">Structure</tt><big>(</big><em>*args</em>, <em>**kw</em><big>)</big><a class="headerlink" href="#ctypes.Structure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>native</em> byte order.</p>
<p>Concrete structure and union types must be created by subclassing one of these
types, and at least define a <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> class variable. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> will
create <a class="reference internal" href="../glossary.html#term-descriptor"><em class="xref std std-term">descriptor</em></a>s which allow reading and writing the fields by direct
attribute accesses.  These are the</p>
<dl class="attribute">
<dt id="ctypes.Structure._fields_">
<tt class="descname">_fields_</tt><a class="headerlink" href="#ctypes.Structure._fields_" title="Permalink to this definition">¶</a></dt>
<dd><p>A sequence defining the structure fields.  The items must be 2-tuples or
3-tuples.  The first item is the name of the field, the second item
specifies the type of the field; it can be any ctypes data type.</p>
<p>For integer type fields like <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><tt class="xref py py-class docutils literal"><span class="pre">c_int</span></tt></a>, a third optional item can be
given.  It must be a small positive integer defining the bit width of the
field.</p>
<p>Field names must be unique within one structure or union.  This is not
checked, only one field can be accessed when names are repeated.</p>
<p>It is possible to define the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> class variable <em>after</em> the
class statement that defines the Structure subclass, this allows to create
data types that directly or indirectly reference themselves:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">List</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
    <span class="k">pass</span>
<span class="n">List</span><span class="o">.</span><span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;pnext&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">List</span><span class="p">)),</span>
                 <span class="o">...</span>
                <span class="p">]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> class variable must, however, be defined before the
type is first used (an instance is created, <a class="reference internal" href="#ctypes.sizeof" title="ctypes.sizeof"><tt class="xref py py-func docutils literal"><span class="pre">sizeof()</span></tt></a> is called on it,
and so on).  Later assignments to the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> class variable will
raise an AttributeError.</p>
<p>Structure and union subclass constructors accept both positional and named
arguments.  Positional arguments are used to initialize the fields in the
same order as they appear in the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> definition, named
arguments are used to initialize the fields with the corresponding name.</p>
<p>It is possible to defined sub-subclasses of structure types, they inherit
the fields of the base class plus the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> defined in the
sub-subclass, if any.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.Structure._pack_">
<tt class="descname">_pack_</tt><a class="headerlink" href="#ctypes.Structure._pack_" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional small integer that allows to override the alignment of
structure fields in the instance.  <a class="reference internal" href="#ctypes.Structure._pack_" title="ctypes.Structure._pack_"><tt class="xref py py-attr docutils literal"><span class="pre">_pack_</span></tt></a> must already be defined
when <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> is assigned, otherwise it will have no effect.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.Structure._anonymous_">
<tt class="descname">_anonymous_</tt><a class="headerlink" href="#ctypes.Structure._anonymous_" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional sequence that lists the names of unnamed (anonymous) fields.
<a class="reference internal" href="#ctypes.Structure._anonymous_" title="ctypes.Structure._anonymous_"><tt class="xref py py-attr docutils literal"><span class="pre">_anonymous_</span></tt></a> must be already defined when <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> is
assigned, otherwise it will have no effect.</p>
<p>The fields listed in this variable must be structure or union type fields.
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><tt class="xref py py-mod docutils literal"><span class="pre">ctypes</span></tt></a> will create descriptors in the structure type that allows to
access the nested fields directly, without the need to create the
structure or union field.</p>
<p>Here is an example type (Windows):</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="k">class</span> <span class="nc">_U</span><span class="p">(</span><span class="n">Union</span><span class="p">):</span>
    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;lptdesc&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">TYPEDESC</span><span class="p">)),</span>
                <span class="p">(</span><span class="s">&quot;lpadesc&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">ARRAYDESC</span><span class="p">)),</span>
                <span class="p">(</span><span class="s">&quot;hreftype&quot;</span><span class="p">,</span> <span class="n">HREFTYPE</span><span class="p">)]</span>

<span class="k">class</span> <span class="nc">TYPEDESC</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
    <span class="n">_anonymous_</span> <span class="o">=</span> <span class="p">(</span><span class="s">&quot;u&quot;</span><span class="p">,)</span>
    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s">&quot;u&quot;</span><span class="p">,</span> <span class="n">_U</span><span class="p">),</span>
                <span class="p">(</span><span class="s">&quot;vt&quot;</span><span class="p">,</span> <span class="n">VARTYPE</span><span class="p">)]</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">TYPEDESC</span></tt> structure describes a COM data type, the <tt class="docutils literal"><span class="pre">vt</span></tt> field
specifies which one of the union fields is valid.  Since the <tt class="docutils literal"><span class="pre">u</span></tt> field
is defined as anonymous field, it is now possible to access the members
directly off the TYPEDESC instance. <tt class="docutils literal"><span class="pre">td.lptdesc</span></tt> and <tt class="docutils literal"><span class="pre">td.u.lptdesc</span></tt>
are equivalent, but the former is faster since it does not need to create
a temporary union instance:</p>
<div class="highlight-python3"><div class="highlight"><pre><span class="n">td</span> <span class="o">=</span> <span class="n">TYPEDESC</span><span class="p">()</span>
<span class="n">td</span><span class="o">.</span><span class="n">vt</span> <span class="o">=</span> <span class="n">VT_PTR</span>
<span class="n">td</span><span class="o">.</span><span class="n">lptdesc</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">some_type</span><span class="p">)</span>
<span class="n">td</span><span class="o">.</span><span class="n">u</span><span class="o">.</span><span class="n">lptdesc</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">some_type</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<p>It is possible to defined sub-subclasses of structures, they inherit the
fields of the base class.  If the subclass definition has a separate
<a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> variable, the fields specified in this are appended to the
fields of the base class.</p>
<p>Structure and union constructors accept both positional and keyword
arguments.  Positional arguments are used to initialize member fields in the
same order as they are appear in <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a>.  Keyword arguments in the
constructor are interpreted as attribute assignments, so they will initialize
<a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a> with the same name, or create new attributes for names not
present in <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><tt class="xref py py-attr docutils literal"><span class="pre">_fields_</span></tt></a>.</p>
</dd></dl>

</div>
<div class="section" id="arrays-and-pointers">
<span id="ctypes-arrays-pointers"></span><h3>15.17.2.9. Arrays and pointers<a class="headerlink" href="#arrays-and-pointers" title="Permalink to this headline">¶</a></h3>
<p>Not yet written - please see the sections <a class="reference internal" href="#ctypes-pointers"><em>Pointers</em></a> and section
<a class="reference internal" href="#ctypes-arrays"><em>Arrays</em></a> in the tutorial.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.17. <tt class="docutils literal"><span class="pre">ctypes</span></tt> &#8212; A foreign function library for Python</a><ul>
<li><a class="reference internal" href="#ctypes-tutorial">15.17.1. ctypes tutorial</a><ul>
<li><a class="reference internal" href="#loading-dynamic-link-libraries">15.17.1.1. Loading dynamic link libraries</a></li>
<li><a class="reference internal" href="#accessing-functions-from-loaded-dlls">15.17.1.2. Accessing functions from loaded dlls</a></li>
<li><a class="reference internal" href="#calling-functions">15.17.1.3. Calling functions</a></li>
<li><a class="reference internal" href="#fundamental-data-types">15.17.1.4. Fundamental data types</a></li>
<li><a class="reference internal" href="#calling-functions-continued">15.17.1.5. Calling functions, continued</a></li>
<li><a class="reference internal" href="#calling-functions-with-your-own-custom-data-types">15.17.1.6. Calling functions with your own custom data types</a></li>
<li><a class="reference internal" href="#specifying-the-required-argument-types-function-prototypes">15.17.1.7. Specifying the required argument types (function prototypes)</a></li>
<li><a class="reference internal" href="#return-types">15.17.1.8. Return types</a></li>
<li><a class="reference internal" href="#passing-pointers-or-passing-parameters-by-reference">15.17.1.9. Passing pointers (or: passing parameters by reference)</a></li>
<li><a class="reference internal" href="#structures-and-unions">15.17.1.10. Structures and unions</a></li>
<li><a class="reference internal" href="#structure-union-alignment-and-byte-order">15.17.1.11. Structure/union alignment and byte order</a></li>
<li><a class="reference internal" href="#bit-fields-in-structures-and-unions">15.17.1.12. Bit fields in structures and unions</a></li>
<li><a class="reference internal" href="#arrays">15.17.1.13. Arrays</a></li>
<li><a class="reference internal" href="#pointers">15.17.1.14. Pointers</a></li>
<li><a class="reference internal" href="#type-conversions">15.17.1.15. Type conversions</a></li>
<li><a class="reference internal" href="#incomplete-types">15.17.1.16. Incomplete Types</a></li>
<li><a class="reference internal" href="#callback-functions">15.17.1.17. Callback functions</a></li>
<li><a class="reference internal" href="#accessing-values-exported-from-dlls">15.17.1.18. Accessing values exported from dlls</a></li>
<li><a class="reference internal" href="#surprises">15.17.1.19. Surprises</a></li>
<li><a class="reference internal" href="#variable-sized-data-types">15.17.1.20. Variable-sized data types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#ctypes-reference">15.17.2. ctypes reference</a><ul>
<li><a class="reference internal" href="#finding-shared-libraries">15.17.2.1. Finding shared libraries</a></li>
<li><a class="reference internal" href="#loading-shared-libraries">15.17.2.2. Loading shared libraries</a></li>
<li><a class="reference internal" href="#foreign-functions">15.17.2.3. Foreign functions</a></li>
<li><a class="reference internal" href="#function-prototypes">15.17.2.4. Function prototypes</a></li>
<li><a class="reference internal" href="#utility-functions">15.17.2.5. Utility functions</a></li>
<li><a class="reference internal" href="#data-types">15.17.2.6. Data types</a></li>
<li><a class="reference internal" href="#ctypes-fundamental-data-types-2">15.17.2.7. Fundamental data types</a></li>
<li><a class="reference internal" href="#structured-data-types">15.17.2.8. Structured data types</a></li>
<li><a class="reference internal" href="#arrays-and-pointers">15.17.2.9. Arrays and pointers</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="errno.html"
                        title="previous chapter">15.16. <tt class="docutils literal"><span class="pre">errno</span></tt> &#8212; Standard errno system symbols</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="someos.html"
                        title="next chapter">16. Optional Operating System Services</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/library/ctypes.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             >next</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v3.2.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" >15. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2011, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Sep 04, 2011.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>