1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5
<html xmlns="http://www.w3.org/1999/xhtml">
7
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
9
<title>1. Embedding Python in Another Application — Python 3.5.1 documentation</title>
11
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
12
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
14
<script type="text/javascript">
15
var DOCUMENTATION_OPTIONS = {
18
COLLAPSE_INDEX: false,
23
<script type="text/javascript" src="../_static/jquery.js"></script>
24
<script type="text/javascript" src="../_static/underscore.js"></script>
25
<script type="text/javascript" src="../_static/doctools.js"></script>
26
<script type="text/javascript" src="../_static/sidebar.js"></script>
27
<link rel="search" type="application/opensearchdescription+xml"
28
title="Search within Python 3.5.1 documentation"
29
href="../_static/opensearch.xml"/>
30
<link rel="author" title="About these documents" href="../about.html" />
31
<link rel="copyright" title="Copyright" href="../copyright.html" />
32
<link rel="top" title="Python 3.5.1 documentation" href="../contents.html" />
33
<link rel="up" title="Extending and Embedding the Python Interpreter" href="index.html" />
34
<link rel="next" title="Python/C API Reference Manual" href="../c-api/index.html" />
35
<link rel="prev" title="4. Building C and C++ Extensions on Windows" href="windows.html" />
36
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
37
<script type="text/javascript" src="../_static/copybutton.js"></script>
38
<script type="text/javascript" src="../_static/version_switch.js"></script>
43
<body role="document">
44
<div class="related" role="navigation" aria-label="related navigation">
47
<li class="right" style="margin-right: 10px">
48
<a href="../genindex.html" title="General Index"
49
accesskey="I">index</a></li>
51
<a href="../py-modindex.html" title="Python Module Index"
54
<a href="../c-api/index.html" title="Python/C API Reference Manual"
55
accesskey="N">next</a> |</li>
57
<a href="windows.html" title="4. Building C and C++ Extensions on Windows"
58
accesskey="P">previous</a> |</li>
59
<li><img src="../_static/py.png" alt=""
60
style="vertical-align: middle; margin-top: -1px"/></li>
61
<li><a href="https://www.python.org/">Python</a> »</li>
63
<span class="version_switcher_placeholder">3.5.1</span>
64
<a href="../index.html">Documentation </a> »
67
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> »</li>
71
<div class="document">
72
<div class="documentwrapper">
73
<div class="bodywrapper">
74
<div class="body" role="main">
76
<div class="section" id="embedding-python-in-another-application">
77
<span id="embedding"></span><h1>1. Embedding Python in Another Application<a class="headerlink" href="#embedding-python-in-another-application" title="Permalink to this headline">¶</a></h1>
78
<p>The previous chapters discussed how to extend Python, that is, how to extend the
79
functionality of Python by attaching a library of C functions to it. It is also
80
possible to do it the other way around: enrich your C/C++ application by
81
embedding Python in it. Embedding provides your application with the ability to
82
implement some of the functionality of your application in Python rather than C
83
or C++. This can be used for many purposes; one example would be to allow users
84
to tailor the application to their needs by writing some scripts in Python. You
85
can also use it yourself if some of the functionality can be written in Python
87
<p>Embedding Python is similar to extending it, but not quite. The difference is
88
that when you extend Python, the main program of the application is still the
89
Python interpreter, while if you embed Python, the main program may have nothing
90
to do with Python — instead, some parts of the application occasionally call
91
the Python interpreter to run some Python code.</p>
92
<p>So if you are embedding Python, you are providing your own main program. One of
93
the things this main program has to do is initialize the Python interpreter. At
94
the very least, you have to call the function <a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal"><span class="pre">Py_Initialize()</span></code></a>. There are
95
optional calls to pass command line arguments to Python. Then later you can
96
call the interpreter from any part of the application.</p>
97
<p>There are several different ways to call the interpreter: you can pass a string
98
containing Python statements to <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal"><span class="pre">PyRun_SimpleString()</span></code></a>, or you can pass a
99
stdio file pointer and a file name (for identification in error messages only)
100
to <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleFile" title="PyRun_SimpleFile"><code class="xref c c-func docutils literal"><span class="pre">PyRun_SimpleFile()</span></code></a>. You can also call the lower-level operations
101
described in the previous chapters to construct and use Python objects.</p>
102
<div class="admonition seealso">
103
<p class="first admonition-title">See also</p>
104
<dl class="last docutils">
105
<dt><a class="reference internal" href="../c-api/index.html#c-api-index"><span>Python/C API Reference Manual</span></a></dt>
106
<dd>The details of Python’s C interface are given in this manual. A great deal of
107
necessary information can be found here.</dd>
110
<div class="section" id="very-high-level-embedding">
111
<span id="high-level-embedding"></span><h2>1.1. Very High Level Embedding<a class="headerlink" href="#very-high-level-embedding" title="Permalink to this headline">¶</a></h2>
112
<p>The simplest form of embedding Python is the use of the very high level
113
interface. This interface is intended to execute a Python script without needing
114
to interact with the application directly. This can for example be used to
115
perform some operation on a file.</p>
116
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><Python.h></span><span class="cp"></span>
118
<span class="kt">int</span>
119
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
120
<span class="p">{</span>
121
<span class="kt">wchar_t</span> <span class="o">*</span><span class="n">program</span> <span class="o">=</span> <span class="n">Py_DecodeLocale</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">);</span>
122
<span class="k">if</span> <span class="p">(</span><span class="n">program</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
123
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Fatal error: cannot decode argv[0]</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
124
<span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
125
<span class="p">}</span>
126
<span class="n">Py_SetProgramName</span><span class="p">(</span><span class="n">program</span><span class="p">);</span> <span class="cm">/* optional but recommended */</span>
127
<span class="n">Py_Initialize</span><span class="p">();</span>
128
<span class="n">PyRun_SimpleString</span><span class="p">(</span><span class="s">"from time import time,ctime</span><span class="se">\n</span><span class="s">"</span>
129
<span class="s">"print('Today is', ctime(time()))</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
130
<span class="n">Py_Finalize</span><span class="p">();</span>
131
<span class="n">PyMem_RawFree</span><span class="p">(</span><span class="n">program</span><span class="p">);</span>
132
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
133
<span class="p">}</span>
136
<p>The <a class="reference internal" href="../c-api/init.html#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal"><span class="pre">Py_SetProgramName()</span></code></a> function should be called before
137
<a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal"><span class="pre">Py_Initialize()</span></code></a> to inform the interpreter about paths to Python run-time
138
libraries. Next, the Python interpreter is initialized with
139
<a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal"><span class="pre">Py_Initialize()</span></code></a>, followed by the execution of a hard-coded Python script
140
that prints the date and time. Afterwards, the <a class="reference internal" href="../c-api/init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal"><span class="pre">Py_Finalize()</span></code></a> call shuts
141
the interpreter down, followed by the end of the program. In a real program,
142
you may want to get the Python script from another source, perhaps a text-editor
143
routine, a file, or a database. Getting the Python code from a file can better
144
be done by using the <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleFile" title="PyRun_SimpleFile"><code class="xref c c-func docutils literal"><span class="pre">PyRun_SimpleFile()</span></code></a> function, which saves you the
145
trouble of allocating memory space and loading the file contents.</p>
147
<div class="section" id="beyond-very-high-level-embedding-an-overview">
148
<span id="lower-level-embedding"></span><h2>1.2. Beyond Very High Level Embedding: An overview<a class="headerlink" href="#beyond-very-high-level-embedding-an-overview" title="Permalink to this headline">¶</a></h2>
149
<p>The high level interface gives you the ability to execute arbitrary pieces of
150
Python code from your application, but exchanging data values is quite
151
cumbersome to say the least. If you want that, you should use lower level calls.
152
At the cost of having to write more C code, you can achieve almost anything.</p>
153
<p>It should be noted that extending Python and embedding Python is quite the same
154
activity, despite the different intent. Most topics discussed in the previous
155
chapters are still valid. To show this, consider what the extension code from
156
Python to C really does:</p>
157
<ol class="arabic simple">
158
<li>Convert data values from Python to C,</li>
159
<li>Perform a function call to a C routine using the converted values, and</li>
160
<li>Convert the data values from the call from C to Python.</li>
162
<p>When embedding Python, the interface code does:</p>
163
<ol class="arabic simple">
164
<li>Convert data values from C to Python,</li>
165
<li>Perform a function call to a Python interface routine using the converted
167
<li>Convert the data values from the call from Python to C.</li>
169
<p>As you can see, the data conversion steps are simply swapped to accommodate the
170
different direction of the cross-language transfer. The only difference is the
171
routine that you call between both data conversions. When extending, you call a
172
C routine, when embedding, you call a Python routine.</p>
173
<p>This chapter will not discuss how to convert data from Python to C and vice
174
versa. Also, proper use of references and dealing with errors is assumed to be
175
understood. Since these aspects do not differ from extending the interpreter,
176
you can refer to earlier chapters for the required information.</p>
178
<div class="section" id="pure-embedding">
179
<span id="id1"></span><h2>1.3. Pure Embedding<a class="headerlink" href="#pure-embedding" title="Permalink to this headline">¶</a></h2>
180
<p>The first program aims to execute a function in a Python script. Like in the
181
section about the very high level interface, the Python interpreter does not
182
directly interact with the application (but that will change in the next
184
<p>The code to run a function defined in a Python script is:</p>
185
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><Python.h></span><span class="cp"></span>
187
<span class="kt">int</span>
188
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
189
<span class="p">{</span>
190
<span class="n">PyObject</span> <span class="o">*</span><span class="n">pName</span><span class="p">,</span> <span class="o">*</span><span class="n">pModule</span><span class="p">,</span> <span class="o">*</span><span class="n">pDict</span><span class="p">,</span> <span class="o">*</span><span class="n">pFunc</span><span class="p">;</span>
191
<span class="n">PyObject</span> <span class="o">*</span><span class="n">pArgs</span><span class="p">,</span> <span class="o">*</span><span class="n">pValue</span><span class="p">;</span>
192
<span class="kt">int</span> <span class="n">i</span><span class="p">;</span>
194
<span class="k">if</span> <span class="p">(</span><span class="n">argc</span> <span class="o"><</span> <span class="mi">3</span><span class="p">)</span> <span class="p">{</span>
195
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="s">"Usage: call pythonfile funcname [args]</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
196
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
197
<span class="p">}</span>
199
<span class="n">Py_Initialize</span><span class="p">();</span>
200
<span class="n">pName</span> <span class="o">=</span> <span class="n">PyUnicode_DecodeFSDefault</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
201
<span class="cm">/* Error checking of pName left out */</span>
203
<span class="n">pModule</span> <span class="o">=</span> <span class="n">PyImport_Import</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>
204
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>
206
<span class="k">if</span> <span class="p">(</span><span class="n">pModule</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
207
<span class="n">pFunc</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">pModule</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
208
<span class="cm">/* pFunc is a new reference */</span>
210
<span class="k">if</span> <span class="p">(</span><span class="n">pFunc</span> <span class="o">&&</span> <span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">pFunc</span><span class="p">))</span> <span class="p">{</span>
211
<span class="n">pArgs</span> <span class="o">=</span> <span class="n">PyTuple_New</span><span class="p">(</span><span class="n">argc</span> <span class="o">-</span> <span class="mi">3</span><span class="p">);</span>
212
<span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o"><</span> <span class="n">argc</span> <span class="o">-</span> <span class="mi">3</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
213
<span class="n">pValue</span> <span class="o">=</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">atoi</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]));</span>
214
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">pValue</span><span class="p">)</span> <span class="p">{</span>
215
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pArgs</span><span class="p">);</span>
216
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
217
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Cannot convert argument</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
218
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
219
<span class="p">}</span>
220
<span class="cm">/* pValue reference stolen here: */</span>
221
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">pArgs</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">pValue</span><span class="p">);</span>
222
<span class="p">}</span>
223
<span class="n">pValue</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">pFunc</span><span class="p">,</span> <span class="n">pArgs</span><span class="p">);</span>
224
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pArgs</span><span class="p">);</span>
225
<span class="k">if</span> <span class="p">(</span><span class="n">pValue</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
226
<span class="n">printf</span><span class="p">(</span><span class="s">"Result of call: %ld</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">PyLong_AsLong</span><span class="p">(</span><span class="n">pValue</span><span class="p">));</span>
227
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pValue</span><span class="p">);</span>
228
<span class="p">}</span>
229
<span class="k">else</span> <span class="p">{</span>
230
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
231
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
232
<span class="n">PyErr_Print</span><span class="p">();</span>
233
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="s">"Call failed</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
234
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
235
<span class="p">}</span>
236
<span class="p">}</span>
237
<span class="k">else</span> <span class="p">{</span>
238
<span class="k">if</span> <span class="p">(</span><span class="n">PyErr_Occurred</span><span class="p">())</span>
239
<span class="n">PyErr_Print</span><span class="p">();</span>
240
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Cannot find function </span><span class="se">\"</span><span class="s">%s</span><span class="se">\"\n</span><span class="s">"</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
241
<span class="p">}</span>
242
<span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
243
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
244
<span class="p">}</span>
245
<span class="k">else</span> <span class="p">{</span>
246
<span class="n">PyErr_Print</span><span class="p">();</span>
247
<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Failed to load </span><span class="se">\"</span><span class="s">%s</span><span class="se">\"\n</span><span class="s">"</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
248
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
249
<span class="p">}</span>
250
<span class="n">Py_Finalize</span><span class="p">();</span>
251
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
252
<span class="p">}</span>
255
<p>This code loads a Python script using <code class="docutils literal"><span class="pre">argv[1]</span></code>, and calls the function named
256
in <code class="docutils literal"><span class="pre">argv[2]</span></code>. Its integer arguments are the other values of the <code class="docutils literal"><span class="pre">argv</span></code>
257
array. If you <a class="reference internal" href="#compiling"><span>compile and link</span></a> this program (let’s call
258
the finished executable <strong class="program">call</strong>), and use it to execute a Python
260
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">):</span>
261
<span class="k">print</span><span class="p">(</span><span class="s2">"Will compute"</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="s2">"times"</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
262
<span class="n">c</span> <span class="o">=</span> <span class="mi">0</span>
263
<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">0</span><span class="p">,</span> <span class="n">a</span><span class="p">):</span>
264
<span class="n">c</span> <span class="o">=</span> <span class="n">c</span> <span class="o">+</span> <span class="n">b</span>
265
<span class="k">return</span> <span class="n">c</span>
268
<p>then the result should be:</p>
269
<div class="highlight-c"><div class="highlight"><pre>$ call multiply multiply 3 2
270
Will compute 3 times 2
274
<p>Although the program is quite large for its functionality, most of the code is
275
for data conversion between Python and C, and for error reporting. The
276
interesting part with respect to embedding Python starts with</p>
277
<div class="highlight-c"><div class="highlight"><pre><span class="n">Py_Initialize</span><span class="p">();</span>
278
<span class="n">pName</span> <span class="o">=</span> <span class="n">PyUnicode_DecodeFSDefault</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
279
<span class="cm">/* Error checking of pName left out */</span>
280
<span class="n">pModule</span> <span class="o">=</span> <span class="n">PyImport_Import</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>
283
<p>After initializing the interpreter, the script is loaded using
284
<a class="reference internal" href="../c-api/import.html#c.PyImport_Import" title="PyImport_Import"><code class="xref c c-func docutils literal"><span class="pre">PyImport_Import()</span></code></a>. This routine needs a Python string as its argument,
285
which is constructed using the <a class="reference internal" href="../c-api/unicode.html#c.PyUnicode_FromString" title="PyUnicode_FromString"><code class="xref c c-func docutils literal"><span class="pre">PyUnicode_FromString()</span></code></a> data conversion
287
<div class="highlight-c"><div class="highlight"><pre><span class="n">pFunc</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">pModule</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
288
<span class="cm">/* pFunc is a new reference */</span>
290
<span class="k">if</span> <span class="p">(</span><span class="n">pFunc</span> <span class="o">&&</span> <span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">pFunc</span><span class="p">))</span> <span class="p">{</span>
291
<span class="p">...</span>
292
<span class="p">}</span>
293
<span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
296
<p>Once the script is loaded, the name we’re looking for is retrieved using
297
<a class="reference internal" href="../c-api/object.html#c.PyObject_GetAttrString" title="PyObject_GetAttrString"><code class="xref c c-func docutils literal"><span class="pre">PyObject_GetAttrString()</span></code></a>. If the name exists, and the object returned is
298
callable, you can safely assume that it is a function. The program then
299
proceeds by constructing a tuple of arguments as normal. The call to the Python
300
function is then made with:</p>
301
<div class="highlight-c"><div class="highlight"><pre><span class="n">pValue</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">pFunc</span><span class="p">,</span> <span class="n">pArgs</span><span class="p">);</span>
304
<p>Upon return of the function, <code class="docutils literal"><span class="pre">pValue</span></code> is either <em>NULL</em> or it contains a
305
reference to the return value of the function. Be sure to release the reference
306
after examining the value.</p>
308
<div class="section" id="extending-embedded-python">
309
<span id="extending-with-embedding"></span><h2>1.4. Extending Embedded Python<a class="headerlink" href="#extending-embedded-python" title="Permalink to this headline">¶</a></h2>
310
<p>Until now, the embedded Python interpreter had no access to functionality from
311
the application itself. The Python API allows this by extending the embedded
312
interpreter. That is, the embedded interpreter gets extended with routines
313
provided by the application. While it sounds complex, it is not so bad. Simply
314
forget for a while that the application starts the Python interpreter. Instead,
315
consider the application to be a set of subroutines, and write some glue code
316
that gives Python access to those routines, just like you would write a normal
317
Python extension. For example:</p>
318
<div class="highlight-c"><div class="highlight"><pre><span class="k">static</span> <span class="kt">int</span> <span class="n">numargs</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span>
320
<span class="cm">/* Return the number of arguments of the application command line */</span>
321
<span class="k">static</span> <span class="n">PyObject</span><span class="o">*</span>
322
<span class="nf">emb_numargs</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
323
<span class="p">{</span>
324
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">":numargs"</span><span class="p">))</span>
325
<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
326
<span class="k">return</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">numargs</span><span class="p">);</span>
327
<span class="p">}</span>
329
<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">EmbMethods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
330
<span class="p">{</span><span class="s">"numargs"</span><span class="p">,</span> <span class="n">emb_numargs</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
331
<span class="s">"Return the number of arguments received by the process."</span><span class="p">},</span>
332
<span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>
333
<span class="p">};</span>
335
<span class="k">static</span> <span class="n">PyModuleDef</span> <span class="n">EmbModule</span> <span class="o">=</span> <span class="p">{</span>
336
<span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span> <span class="s">"emb"</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">EmbMethods</span><span class="p">,</span>
337
<span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span>
338
<span class="p">};</span>
340
<span class="k">static</span> <span class="n">PyObject</span><span class="o">*</span>
341
<span class="nf">PyInit_emb</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
342
<span class="p">{</span>
343
<span class="k">return</span> <span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&</span><span class="n">EmbModule</span><span class="p">);</span>
344
<span class="p">}</span>
347
<p>Insert the above code just above the <code class="xref c c-func docutils literal"><span class="pre">main()</span></code> function. Also, insert the
348
following two statements before the call to <a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal"><span class="pre">Py_Initialize()</span></code></a>:</p>
349
<div class="highlight-c"><div class="highlight"><pre><span class="n">numargs</span> <span class="o">=</span> <span class="n">argc</span><span class="p">;</span>
350
<span class="n">PyImport_AppendInittab</span><span class="p">(</span><span class="s">"emb"</span><span class="p">,</span> <span class="o">&</span><span class="n">PyInit_emb</span><span class="p">);</span>
353
<p>These two lines initialize the <code class="docutils literal"><span class="pre">numargs</span></code> variable, and make the
354
<code class="xref py py-func docutils literal"><span class="pre">emb.numargs()</span></code> function accessible to the embedded Python interpreter.
355
With these extensions, the Python script can do things like</p>
356
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">emb</span>
357
<span class="k">print</span><span class="p">(</span><span class="s2">"Number of arguments"</span><span class="p">,</span> <span class="n">emb</span><span class="o">.</span><span class="n">numargs</span><span class="p">())</span>
360
<p>In a real application, the methods will expose an API of the application to
363
<div class="section" id="embedding-python-in-c">
364
<span id="embeddingincplusplus"></span><h2>1.5. Embedding Python in C++<a class="headerlink" href="#embedding-python-in-c" title="Permalink to this headline">¶</a></h2>
365
<p>It is also possible to embed Python in a C++ program; precisely how this is done
366
will depend on the details of the C++ system used; in general you will need to
367
write the main program in C++, and use the C++ compiler to compile and link your
368
program. There is no need to recompile Python itself using C++.</p>
370
<div class="section" id="compiling-and-linking-under-unix-like-systems">
371
<span id="compiling"></span><h2>1.6. Compiling and Linking under Unix-like systems<a class="headerlink" href="#compiling-and-linking-under-unix-like-systems" title="Permalink to this headline">¶</a></h2>
372
<p>It is not necessarily trivial to find the right flags to pass to your
373
compiler (and linker) in order to embed the Python interpreter into your
374
application, particularly because Python needs to load library modules
375
implemented as C dynamic extensions (<code class="file docutils literal"><span class="pre">.so</span></code> files) linked against
377
<p>To find out the required compiler and linker flags, you can execute the
378
<code class="file docutils literal"><span class="pre">python</span><em><span class="pre">X.Y</span></em><span class="pre">-config</span></code> script which is generated as part of the
379
installation process (a <code class="file docutils literal"><span class="pre">python3-config</span></code> script may also be
380
available). This script has several options, of which the following will
381
be directly useful to you:</p>
383
<li><p class="first"><code class="docutils literal"><span class="pre">pythonX.Y-config</span> <span class="pre">--cflags</span></code> will give you the recommended flags when
385
<div class="highlight-c"><div class="highlight"><pre>$ /opt/bin/python3.4-config --cflags
386
-I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
390
<li><p class="first"><code class="docutils literal"><span class="pre">pythonX.Y-config</span> <span class="pre">--ldflags</span></code> will give you the recommended flags when
392
<div class="highlight-c"><div class="highlight"><pre>$ /opt/bin/python3.4-config --ldflags
393
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
398
<div class="admonition note">
399
<p class="first admonition-title">Note</p>
400
<p class="last">To avoid confusion between several Python installations (and especially
401
between the system Python and your own compiled Python), it is recommended
402
that you use the absolute path to <code class="file docutils literal"><span class="pre">python</span><em><span class="pre">X.Y</span></em><span class="pre">-config</span></code>, as in the above
405
<p>If this procedure doesn’t work for you (it is not guaranteed to work for
406
all Unix-like platforms; however, we welcome <a class="reference internal" href="../bugs.html#reporting-bugs"><span>bug reports</span></a>)
407
you will have to read your system’s documentation about dynamic linking and/or
408
examine Python’s <code class="file docutils literal"><span class="pre">Makefile</span></code> (use <a class="reference internal" href="../library/sysconfig.html#sysconfig.get_makefile_filename" title="sysconfig.get_makefile_filename"><code class="xref py py-func docutils literal"><span class="pre">sysconfig.get_makefile_filename()</span></code></a>
409
to find its location) and compilation
410
options. In this case, the <a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal"><span class="pre">sysconfig</span></code></a> module is a useful tool to
411
programmatically extract the configuration values that you will want to
412
combine together. For example:</p>
413
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">sysconfig</span>
414
<span class="gp">>>> </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">'LIBS'</span><span class="p">)</span>
415
<span class="go">'-lpthread -ldl -lutil'</span>
416
<span class="gp">>>> </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">'LINKFORSHARED'</span><span class="p">)</span>
417
<span class="go">'-Xlinker -export-dynamic'</span>
427
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
428
<div class="sphinxsidebarwrapper">
429
<h3><a href="../contents.html">Table Of Contents</a></h3>
431
<li><a class="reference internal" href="#">1. Embedding Python in Another Application</a><ul>
432
<li><a class="reference internal" href="#very-high-level-embedding">1.1. Very High Level Embedding</a></li>
433
<li><a class="reference internal" href="#beyond-very-high-level-embedding-an-overview">1.2. Beyond Very High Level Embedding: An overview</a></li>
434
<li><a class="reference internal" href="#pure-embedding">1.3. Pure Embedding</a></li>
435
<li><a class="reference internal" href="#extending-embedded-python">1.4. Extending Embedded Python</a></li>
436
<li><a class="reference internal" href="#embedding-python-in-c">1.5. Embedding Python in C++</a></li>
437
<li><a class="reference internal" href="#compiling-and-linking-under-unix-like-systems">1.6. Compiling and Linking under Unix-like systems</a></li>
442
<h4>Previous topic</h4>
443
<p class="topless"><a href="windows.html"
444
title="previous chapter">4. Building C and C++ Extensions on Windows</a></p>
446
<p class="topless"><a href="../c-api/index.html"
447
title="next chapter">Python/C API Reference Manual</a></p>
449
<ul class="this-page-menu">
450
<li><a href="../bugs.html">Report a Bug</a></li>
451
<li><a href="../_sources/extending/embedding.txt"
452
rel="nofollow">Show Source</a></li>
455
<div id="searchbox" style="display: none" role="search">
456
<h3>Quick search</h3>
457
<form class="search" action="../search.html" method="get">
458
<input type="text" name="q" />
459
<input type="submit" value="Go" />
460
<input type="hidden" name="check_keywords" value="yes" />
461
<input type="hidden" name="area" value="default" />
463
<p class="searchtip" style="font-size: 90%">
464
Enter search terms or a module, class or function name.
467
<script type="text/javascript">$('#searchbox').show(0);</script>
470
<div class="clearer"></div>
472
<div class="related" role="navigation" aria-label="related navigation">
475
<li class="right" style="margin-right: 10px">
476
<a href="../genindex.html" title="General Index"
479
<a href="../py-modindex.html" title="Python Module Index"
482
<a href="../c-api/index.html" title="Python/C API Reference Manual"
485
<a href="windows.html" title="4. Building C and C++ Extensions on Windows"
487
<li><img src="../_static/py.png" alt=""
488
style="vertical-align: middle; margin-top: -1px"/></li>
489
<li><a href="https://www.python.org/">Python</a> »</li>
491
<span class="version_switcher_placeholder">3.5.1</span>
492
<a href="../index.html">Documentation </a> »
495
<li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> »</li>
499
© <a href="../copyright.html">Copyright</a> 1990-2016, Python Software Foundation.
501
The Python Software Foundation is a non-profit corporation.
502
<a href="https://www.python.org/psf/donations/">Please donate.</a>
504
Last updated on Jan 22, 2016.
505
<a href="../bugs.html">Found a bug</a>?
507
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
b'\\ No newline at end of file'