<!DOCTYPE html>

<html lang="en" data-content_root="../">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:title" content="Extending/Embedding FAQ" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://docs.python.org/3/faq/extending.html" />
<meta property="og:site_name" content="Python documentation" />
<meta property="og:description" content="Contents: Extending/Embedding FAQ- Can I create my own functions in C?, Can I create my own functions in C++?, Writing C is hard; are there any alternatives?, How can I execute arbitrary Python sta..." />
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
<meta property="og:image:alt" content="Python documentation" />
<meta name="description" content="Contents: Extending/Embedding FAQ- Can I create my own functions in C?, Can I create my own functions in C++?, Writing C is hard; are there any alternatives?, How can I execute arbitrary Python sta..." />
<meta property="og:image:width" content="200">
<meta property="og:image:height" content="200">
<meta name="theme-color" content="#3776ab">

    <title>Extending/Embedding FAQ &#8212; Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
    <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
    <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
    
    <script src="../_static/documentation_options.js?v=5d57ca2d"></script>
    <script src="../_static/doctools.js?v=9bcbadda"></script>
    <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
    
    <script src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.13.3 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python on Windows FAQ" href="windows.html" />
    <link rel="prev" title="Library and Extension FAQ" href="library.html" />
    
    <link rel="canonical" href="https://docs.python.org/3/faq/extending.html">
    
      
    

    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
    <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
            <script type="text/javascript" src="../_static/copybutton.js"></script>
            <script type="text/javascript" src="../_static/menu.js"></script>
            <script type="text/javascript" src="../_static/search-focus.js"></script>
            <script type="text/javascript" src="../_static/themetoggle.js"></script> 
            <script type="text/javascript" src="../_static/rtd_switcher.js"></script>
            <meta name="readthedocs-addons-api-version" content="1">

  </head>
<body>
<div class="mobile-nav">
    <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
           aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
    <nav class="nav-content" role="navigation">
        <label for="menuToggler" class="toggler__label">
            <span></span>
        </label>
        <span class="nav-items-wrapper">
            <a href="https://www.python.org/" class="nav-logo">
                <img src="../_static/py.svg" alt="Python logo"/>
            </a>
            <span class="version_switcher_placeholder"></span>
            <form role="search" class="search" action="../search.html" method="get">
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
                    <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
                </svg>
                <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
                <input type="submit" value="Go"/>
            </form>
        </span>
    </nav>
    <div class="menu-wrapper">
        <nav class="menu" role="navigation" aria-label="main navigation">
            <div class="language_switcher_placeholder"></div>
            
<label class="theme-selector-label">
    Theme
    <select class="theme-selector" oninput="activateTheme(this.value)">
        <option value="auto" selected>Auto</option>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
</label>
  <div>
    <h3><a href="../contents.html">Table of Contents</a></h3>
    <ul>
<li><a class="reference internal" href="#">Extending/Embedding FAQ</a><ul>
<li><a class="reference internal" href="#can-i-create-my-own-functions-in-c">Can I create my own functions in C?</a></li>
<li><a class="reference internal" href="#id1">Can I create my own functions in C++?</a></li>
<li><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives">Writing C is hard; are there any alternatives?</a></li>
<li><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c">How can I execute arbitrary Python statements from C?</a></li>
<li><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c">How can I evaluate an arbitrary Python expression from C?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object">How do I extract C values from a Python object?</a></li>
<li><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
<li><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c">How do I call an object’s method from C?</a></li>
<li><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
<li><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c">How do I access a module written in Python from C?</a></li>
<li><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python">How do I interface to C++ objects from Python?</a></li>
<li><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why">I added a module using the Setup file and the make fails; why?</a></li>
<li><a class="reference internal" href="#how-do-i-debug-an-extension">How do I debug an extension?</a></li>
<li><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
<li><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input">How do I tell “incomplete input” from “invalid input”?</a></li>
<li><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
<li><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
</ul>
</li>
</ul>

  </div>
  <div>
    <h4>Previous topic</h4>
    <p class="topless"><a href="library.html"
                          title="previous chapter">Library and Extension FAQ</a></p>
  </div>
  <div>
    <h4>Next topic</h4>
    <p class="topless"><a href="windows.html"
                          title="next chapter">Python on Windows FAQ</a></p>
  </div>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/main/Doc/faq/extending.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </nav>
    </div>
</div>

  
    <div class="related" role="navigation" aria-label="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="windows.html" title="Python on Windows FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             accesskey="P">previous</a> |</li>

          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.13.3 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="">Extending/Embedding FAQ</a></li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
          <input type="submit" value="Go" />
        </form>
    </div>
                     |
                </li>
            <li class="right">
<label class="theme-selector-label">
    Theme
    <select class="theme-selector" oninput="activateTheme(this.value)">
        <option value="auto" selected>Auto</option>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
</label> |</li>
            
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <section id="extending-embedding-faq">
<h1><a class="toc-backref" href="#id2" role="doc-backlink">Extending/Embedding FAQ</a><a class="headerlink" href="#extending-embedding-faq" title="Link to this heading">¶</a></h1>
<nav class="contents" id="contents">
<p class="topic-title">Contents</p>
<ul class="simple">
<li><p><a class="reference internal" href="#extending-embedding-faq" id="id2">Extending/Embedding FAQ</a></p>
<ul>
<li><p><a class="reference internal" href="#can-i-create-my-own-functions-in-c" id="id3">Can I create my own functions in C?</a></p></li>
<li><p><a class="reference internal" href="#id1" id="id4">Can I create my own functions in C++?</a></p></li>
<li><p><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives" id="id5">Writing C is hard; are there any alternatives?</a></p></li>
<li><p><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c" id="id6">How can I execute arbitrary Python statements from C?</a></p></li>
<li><p><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" id="id7">How can I evaluate an arbitrary Python expression from C?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object" id="id8">How do I extract C values from a Python object?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" id="id9">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c" id="id10">How do I call an object’s method from C?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" id="id11">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c" id="id12">How do I access a module written in Python from C?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python" id="id13">How do I interface to C++ objects from Python?</a></p></li>
<li><p><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" id="id14">I added a module using the Setup file and the make fails; why?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-debug-an-extension" id="id15">How do I debug an extension?</a></p></li>
<li><p><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" id="id16">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input" id="id17">How do I tell “incomplete input” from “invalid input”?</a></p></li>
<li><p><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" id="id18">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></p></li>
<li><p><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" id="id19">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></p></li>
</ul>
</li>
</ul>
</nav>
<section id="can-i-create-my-own-functions-in-c">
<h2><a class="toc-backref" href="#id3" role="doc-backlink">Can I create my own functions in C?</a><a class="headerlink" href="#can-i-create-my-own-functions-in-c" title="Link to this heading">¶</a></h2>
<p>Yes, you can create built-in modules containing functions, variables, exceptions
and even new types in C.  This is explained in the document
<a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a>.</p>
<p>Most intermediate or advanced Python books will also cover this topic.</p>
</section>
<section id="id1">
<h2><a class="toc-backref" href="#id4" role="doc-backlink">Can I create my own functions in C++?</a><a class="headerlink" href="#id1" title="Link to this heading">¶</a></h2>
<p>Yes, using the C compatibility features found in C++.  Place <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span> <span class="pre">{</span>
<span class="pre">...</span> <span class="pre">}</span></code> around the Python include files and put <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code> before each
function that is going to be called by the Python interpreter.  Global or static
C++ objects with constructors are probably not a good idea.</p>
</section>
<section id="writing-c-is-hard-are-there-any-alternatives">
<span id="c-wrapper-software"></span><h2><a class="toc-backref" href="#id5" role="doc-backlink">Writing C is hard; are there any alternatives?</a><a class="headerlink" href="#writing-c-is-hard-are-there-any-alternatives" title="Link to this heading">¶</a></h2>
<p>There are a number of alternatives to writing your own C extensions, depending
on what you’re trying to do.</p>
<p><a class="reference external" href="https://cython.org">Cython</a> and its relative <a class="reference external" href="https://www.csse.canterbury.ac.nz/greg.ewing/python/Pyrex/">Pyrex</a> are compilers
that accept a slightly modified form of Python and generate the corresponding
C code.  Cython and Pyrex make it possible to write an extension without having
to learn Python’s C API.</p>
<p>If you need to interface to some C or C++ library for which no Python extension
currently exists, you can try wrapping the library’s data types and functions
with a tool such as <a class="reference external" href="https://www.swig.org">SWIG</a>.  <a class="reference external" href="https://github.com/Python-SIP/sip">SIP</a>, <a class="reference external" href="https://cxx.sourceforge.net/">CXX</a> <a class="reference external" href="https://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference external" href="https://github.com/scipy/weave">Weave</a> are also
alternatives for wrapping C++ libraries.</p>
</section>
<section id="how-can-i-execute-arbitrary-python-statements-from-c">
<h2><a class="toc-backref" href="#id6" role="doc-backlink">How can I execute arbitrary Python statements from C?</a><a class="headerlink" href="#how-can-i-execute-arbitrary-python-statements-from-c" title="Link to this heading">¶</a></h2>
<p>The highest-level function to do this is <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleString()</span></code></a> which takes
a single string argument to be executed in the context of the module
<code class="docutils literal notranslate"><span class="pre">__main__</span></code> and returns <code class="docutils literal notranslate"><span class="pre">0</span></code> for success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> when an exception occurred
(including <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>).  If you want more control, use
<a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_String" title="PyRun_String"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_String()</span></code></a>; see the source for <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleString()</span></code></a> in
<code class="docutils literal notranslate"><span class="pre">Python/pythonrun.c</span></code>.</p>
</section>
<section id="how-can-i-evaluate-an-arbitrary-python-expression-from-c">
<h2><a class="toc-backref" href="#id7" role="doc-backlink">How can I evaluate an arbitrary Python expression from C?</a><a class="headerlink" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" title="Link to this heading">¶</a></h2>
<p>Call the function <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_String" title="PyRun_String"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_String()</span></code></a> from the previous question with the
start symbol <a class="reference internal" href="../c-api/veryhigh.html#c.Py_eval_input" title="Py_eval_input"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_eval_input</span></code></a>; it parses an expression, evaluates it and
returns its value.</p>
</section>
<section id="how-do-i-extract-c-values-from-a-python-object">
<h2><a class="toc-backref" href="#id8" role="doc-backlink">How do I extract C values from a Python object?</a><a class="headerlink" href="#how-do-i-extract-c-values-from-a-python-object" title="Link to this heading">¶</a></h2>
<p>That depends on the object’s type.  If it’s a tuple, <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_Size" title="PyTuple_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_Size()</span></code></a>
returns its length and <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a> returns the item at a specified
index.  Lists have similar functions, <a class="reference internal" href="../c-api/list.html#c.PyList_Size" title="PyList_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Size()</span></code></a> and
<a class="reference internal" href="../c-api/list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>.</p>
<p>For bytes, <a class="reference internal" href="../c-api/bytes.html#c.PyBytes_Size" title="PyBytes_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_Size()</span></code></a> returns its length and
<a class="reference internal" href="../c-api/bytes.html#c.PyBytes_AsStringAndSize" title="PyBytes_AsStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_AsStringAndSize()</span></code></a> provides a pointer to its value and its
length.  Note that Python bytes objects may contain null bytes so C’s
<code class="xref c c-func docutils literal notranslate"><span class="pre">strlen()</span></code> should not be used.</p>
<p>To test the type of an object, first make sure it isn’t <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, and then use
<a class="reference internal" href="../c-api/bytes.html#c.PyBytes_Check" title="PyBytes_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_Check()</span></code></a>, <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_Check" title="PyTuple_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_Check()</span></code></a>, <a class="reference internal" href="../c-api/list.html#c.PyList_Check" title="PyList_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Check()</span></code></a>, etc.</p>
<p>There is also a high-level API to Python objects which is provided by the
so-called ‘abstract’ interface – read <code class="docutils literal notranslate"><span class="pre">Include/abstract.h</span></code> for further
details.  It allows interfacing with any kind of Python sequence using calls
like <a class="reference internal" href="../c-api/sequence.html#c.PySequence_Length" title="PySequence_Length"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Length()</span></code></a>, <a class="reference internal" href="../c-api/sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>, etc. as well
as many other useful protocols such as numbers (<a class="reference internal" href="../c-api/number.html#c.PyNumber_Index" title="PyNumber_Index"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Index()</span></code></a> et
al.) and mappings in the PyMapping APIs.</p>
</section>
<section id="how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">
<h2><a class="toc-backref" href="#id9" role="doc-backlink">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a><a class="headerlink" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" title="Link to this heading">¶</a></h2>
<p>You can’t.  Use <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_Pack" title="PyTuple_Pack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_Pack()</span></code></a> instead.</p>
</section>
<section id="how-do-i-call-an-object-s-method-from-c">
<h2><a class="toc-backref" href="#id10" role="doc-backlink">How do I call an object’s method from C?</a><a class="headerlink" href="#how-do-i-call-an-object-s-method-from-c" title="Link to this heading">¶</a></h2>
<p>The <a class="reference internal" href="../c-api/call.html#c.PyObject_CallMethod" title="PyObject_CallMethod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallMethod()</span></code></a> function can be used to call an arbitrary
method of an object.  The parameters are the object, the name of the method to
call, a format string like that used with <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, and the
argument values:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span>
<span class="nf">PyObject_CallMethod</span><span class="p">(</span><span class="n">PyObject</span><span class="w"> </span><span class="o">*</span><span class="n">object</span><span class="p">,</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">method_name</span><span class="p">,</span>
<span class="w">                    </span><span class="k">const</span><span class="w"> </span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">arg_format</span><span class="p">,</span><span class="w"> </span><span class="p">...);</span>
</pre></div>
</div>
<p>This works for any object that has methods – whether built-in or user-defined.
You are responsible for eventually <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>‘ing the return value.</p>
<p>To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming the
file object pointer is “f”):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">res</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyObject_CallMethod</span><span class="p">(</span><span class="n">f</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;seek&quot;</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;(ii)&quot;</span><span class="p">,</span><span class="w"> </span><span class="mi">10</span><span class="p">,</span><span class="w"> </span><span class="mi">0</span><span class="p">);</span>
<span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">res</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="nb">NULL</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w">        </span><span class="p">...</span><span class="w"> </span><span class="n">an</span><span class="w"> </span><span class="n">exception</span><span class="w"> </span><span class="n">occurred</span><span class="w"> </span><span class="p">...</span>
<span class="p">}</span>
<span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="w">        </span><span class="n">Py_DECREF</span><span class="p">(</span><span class="n">res</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that since <a class="reference internal" href="../c-api/call.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> <em>always</em> wants a tuple for the
argument list, to call a function without arguments, pass “()” for the format,
and to call a function with one argument, surround the argument in parentheses,
e.g. “(i)”.</p>
</section>
<section id="how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">
<h2><a class="toc-backref" href="#id11" role="doc-backlink">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a><a class="headerlink" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" title="Link to this heading">¶</a></h2>
<p>In Python code, define an object that supports the <code class="docutils literal notranslate"><span class="pre">write()</span></code> method.  Assign
this object to <a class="reference internal" href="../library/sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.  Call print_error, or
just allow the standard traceback mechanism to work. Then, the output will go
wherever your <code class="docutils literal notranslate"><span class="pre">write()</span></code> method sends it.</p>
<p>The easiest way to do this is to use the <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> class:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">io</span><span class="o">,</span><span class="w"> </span><span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello world!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">getvalue</span><span class="p">())</span>
<span class="go">foo</span>
<span class="go">hello world!</span>
</pre></div>
</div>
<p>A custom object to do the same would look like this:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">io</span><span class="o">,</span><span class="w"> </span><span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span><span class="w"> </span><span class="nc">StdoutCatcher</span><span class="p">(</span><span class="n">io</span><span class="o">.</span><span class="n">TextIOBase</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="k">def</span><span class="w"> </span><span class="nf">write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">stuff</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span> <span class="o">=</span> <span class="n">StdoutCatcher</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;hello world!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">data</span><span class="p">))</span>
<span class="go">foo</span>
<span class="go">hello world!</span>
</pre></div>
</div>
</section>
<section id="how-do-i-access-a-module-written-in-python-from-c">
<h2><a class="toc-backref" href="#id12" role="doc-backlink">How do I access a module written in Python from C?</a><a class="headerlink" href="#how-do-i-access-a-module-written-in-python-from-c" title="Link to this heading">¶</a></h2>
<p>You can get a pointer to the module object as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">module</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyImport_ImportModule</span><span class="p">(</span><span class="s">&quot;&lt;modulename&gt;&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>If the module hasn’t been imported yet (i.e. it is not yet present in
<a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>), this initializes the module; otherwise it simply returns
the value of <code class="docutils literal notranslate"><span class="pre">sys.modules[&quot;&lt;modulename&gt;&quot;]</span></code>.  Note that it doesn’t enter the
module into any namespace – it only ensures it has been initialized and is
stored in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p>
<p>You can then access the module’s attributes (i.e. any name defined in the
module) as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">attr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">module</span><span class="p">,</span><span class="w"> </span><span class="s">&quot;&lt;attrname&gt;&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>Calling <a class="reference internal" href="../c-api/object.html#c.PyObject_SetAttrString" title="PyObject_SetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetAttrString()</span></code></a> to assign to variables in the module
also works.</p>
</section>
<section id="how-do-i-interface-to-c-objects-from-python">
<h2><a class="toc-backref" href="#id13" role="doc-backlink">How do I interface to C++ objects from Python?</a><a class="headerlink" href="#how-do-i-interface-to-c-objects-from-python" title="Link to this heading">¶</a></h2>
<p>Depending on your requirements, there are many approaches.  To do this manually,
begin by reading <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">the “Extending and Embedding” document</span></a>.  Realize that for the Python run-time system, there isn’t a
whole lot of difference between C and C++ – so the strategy of building a new
Python type around a C structure (pointer) type will also work for C++ objects.</p>
<p>For C++ libraries, see <a class="reference internal" href="#c-wrapper-software"><span class="std std-ref">Writing C is hard; are there any alternatives?</span></a>.</p>
</section>
<section id="i-added-a-module-using-the-setup-file-and-the-make-fails-why">
<h2><a class="toc-backref" href="#id14" role="doc-backlink">I added a module using the Setup file and the make fails; why?</a><a class="headerlink" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" title="Link to this heading">¶</a></h2>
<p>Setup must end in a newline, if there is no newline there, the build process
fails.  (Fixing this requires some ugly shell script hackery, and this bug is so
minor that it doesn’t seem worth the effort.)</p>
</section>
<section id="how-do-i-debug-an-extension">
<h2><a class="toc-backref" href="#id15" role="doc-backlink">How do I debug an extension?</a><a class="headerlink" href="#how-do-i-debug-an-extension" title="Link to this heading">¶</a></h2>
<p>When using GDB with dynamically loaded extensions, you can’t set a breakpoint in
your extension until your extension is loaded.</p>
<p>In your <code class="docutils literal notranslate"><span class="pre">.gdbinit</span></code> file (or interactively), add the command:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>br _PyImport_LoadDynamicModule
</pre></div>
</div>
<p>Then, when you run GDB:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>gdb<span class="w"> </span>/local/bin/python
<span class="go">gdb) run myscript.py</span>
<span class="go">gdb) continue # repeat until your extension is loaded</span>
<span class="go">gdb) finish   # so that your extension is loaded</span>
<span class="go">gdb) br myfunction.c:50</span>
<span class="go">gdb) continue</span>
</pre></div>
</div>
</section>
<section id="i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">
<h2><a class="toc-backref" href="#id16" role="doc-backlink">I want to compile a Python module on my Linux system, but some files are missing. Why?</a><a class="headerlink" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" title="Link to this heading">¶</a></h2>
<p>Most packaged versions of Python omit some files
required for compiling Python extensions.</p>
<p>For Red Hat, install the python3-devel RPM to get the necessary files.</p>
<p>For Debian, run <code class="docutils literal notranslate"><span class="pre">apt-get</span> <span class="pre">install</span> <span class="pre">python3-dev</span></code>.</p>
</section>
<section id="how-do-i-tell-incomplete-input-from-invalid-input">
<h2><a class="toc-backref" href="#id17" role="doc-backlink">How do I tell “incomplete input” from “invalid input”?</a><a class="headerlink" href="#how-do-i-tell-incomplete-input-from-invalid-input" title="Link to this heading">¶</a></h2>
<p>Sometimes you want to emulate the Python interactive interpreter’s behavior,
where it gives you a continuation prompt when the input is incomplete (e.g. you
typed the start of an “if” statement or you didn’t close your parentheses or
triple string quotes), but it gives you a syntax error message immediately when
the input is invalid.</p>
<p>In Python you can use the <a class="reference internal" href="../library/codeop.html#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> module, which approximates the parser’s
behavior sufficiently.  IDLE uses this, for example.</p>
<p>The easiest way to do it in C is to call <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_InteractiveLoop" title="PyRun_InteractiveLoop"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveLoop()</span></code></a> (perhaps
in a separate thread) and let the Python interpreter handle the input for
you. You can also set the <a class="reference internal" href="../c-api/veryhigh.html#c.PyOS_ReadlineFunctionPointer" title="PyOS_ReadlineFunctionPointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ReadlineFunctionPointer()</span></code></a> to point at your
custom input function. See <code class="docutils literal notranslate"><span class="pre">Modules/readline.c</span></code> and <code class="docutils literal notranslate"><span class="pre">Parser/myreadline.c</span></code>
for more hints.</p>
</section>
<section id="how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">
<h2><a class="toc-backref" href="#id18" role="doc-backlink">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a><a class="headerlink" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" title="Link to this heading">¶</a></h2>
<p>To dynamically load g++ extension modules, you must recompile Python, relink it
using g++ (change LINKCC in the Python Modules Makefile), and link your
extension module using g++ (e.g., <code class="docutils literal notranslate"><span class="pre">g++</span> <span class="pre">-shared</span> <span class="pre">-o</span> <span class="pre">mymodule.so</span> <span class="pre">mymodule.o</span></code>).</p>
</section>
<section id="can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">
<h2><a class="toc-backref" href="#id19" role="doc-backlink">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a><a class="headerlink" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" title="Link to this heading">¶</a></h2>
<p>Yes, you can inherit from built-in classes such as <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>,
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, etc.</p>
<p>The Boost Python Library (BPL, <a class="reference external" href="https://www.boost.org/libs/python/doc/index.html">https://www.boost.org/libs/python/doc/index.html</a>)
provides a way of doing this from C++ (i.e. you can inherit from an extension
class written in C++ using the BPL).</p>
</section>
</section>


            <div class="clearer"></div>
          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="Main">
        <div class="sphinxsidebarwrapper">
  <div>
    <h3><a href="../contents.html">Table of Contents</a></h3>
    <ul>
<li><a class="reference internal" href="#">Extending/Embedding FAQ</a><ul>
<li><a class="reference internal" href="#can-i-create-my-own-functions-in-c">Can I create my own functions in C?</a></li>
<li><a class="reference internal" href="#id1">Can I create my own functions in C++?</a></li>
<li><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives">Writing C is hard; are there any alternatives?</a></li>
<li><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c">How can I execute arbitrary Python statements from C?</a></li>
<li><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c">How can I evaluate an arbitrary Python expression from C?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object">How do I extract C values from a Python object?</a></li>
<li><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
<li><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c">How do I call an object’s method from C?</a></li>
<li><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
<li><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c">How do I access a module written in Python from C?</a></li>
<li><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python">How do I interface to C++ objects from Python?</a></li>
<li><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why">I added a module using the Setup file and the make fails; why?</a></li>
<li><a class="reference internal" href="#how-do-i-debug-an-extension">How do I debug an extension?</a></li>
<li><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
<li><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input">How do I tell “incomplete input” from “invalid input”?</a></li>
<li><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
<li><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
</ul>
</li>
</ul>

  </div>
  <div>
    <h4>Previous topic</h4>
    <p class="topless"><a href="library.html"
                          title="previous chapter">Library and Extension FAQ</a></p>
  </div>
  <div>
    <h4>Next topic</h4>
    <p class="topless"><a href="windows.html"
                          title="next chapter">Python on Windows FAQ</a></p>
  </div>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/main/Doc/faq/extending.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
<div id="sidebarbutton" title="Collapse sidebar">
<span>«</span>
</div>

      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="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="windows.html" title="Python on Windows FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             >previous</a> |</li>

          <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
          <li><a href="https://www.python.org/">Python</a> &#187;</li>
          <li class="switchers">
            <div class="language_switcher_placeholder"></div>
            <div class="version_switcher_placeholder"></div>
          </li>
          <li>
              
          </li>
    <li id="cpython-language-and-version">
      <a href="../index.html">3.13.3 Documentation</a> &#187;
    </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li>
        <li class="nav-item nav-item-this"><a href="">Extending/Embedding FAQ</a></li>
                <li class="right">
                    

    <div class="inline-search" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
          <input type="submit" value="Go" />
        </form>
    </div>
                     |
                </li>
            <li class="right">
<label class="theme-selector-label">
    Theme
    <select class="theme-selector" oninput="activateTheme(this.value)">
        <option value="auto" selected>Auto</option>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
</label> |</li>
            
      </ul>
    </div>  
    <div class="footer">
    &copy; 
      <a href="../copyright.html">
    
    Copyright
    
      </a>
     2001-2025, Python Software Foundation.
    <br />
    This page is licensed under the Python Software Foundation License Version 2.
    <br />
    Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
    <br />
    
      See <a href="/license.html">History and License</a> for more information.<br />
    
    
    <br />

    The Python Software Foundation is a non-profit corporation.
<a href="https://www.python.org/psf/donations/">Please donate.</a>
<br />
    <br />
      Last updated on Apr 08, 2025 (14:33 UTC).
    
      <a href="/bugs.html">Found a bug</a>?
    
    <br />

    Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
    </div>

  </body>
</html>