blob: cc4a70e25440e993c98266014591cf77856ac17d [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. highlightlang:: c
2
3
4.. _embedding:
5
6***************************************
7Embedding Python in Another Application
8***************************************
9
10The previous chapters discussed how to extend Python, that is, how to extend the
11functionality of Python by attaching a library of C functions to it. It is also
12possible to do it the other way around: enrich your C/C++ application by
13embedding Python in it. Embedding provides your application with the ability to
14implement some of the functionality of your application in Python rather than C
15or C++. This can be used for many purposes; one example would be to allow users
16to tailor the application to their needs by writing some scripts in Python. You
17can also use it yourself if some of the functionality can be written in Python
18more easily.
19
20Embedding Python is similar to extending it, but not quite. The difference is
21that when you extend Python, the main program of the application is still the
22Python interpreter, while if you embed Python, the main program may have nothing
23to do with Python --- instead, some parts of the application occasionally call
24the Python interpreter to run some Python code.
25
26So if you are embedding Python, you are providing your own main program. One of
27the things this main program has to do is initialize the Python interpreter. At
Sandro Tosi98ed08f2012-01-14 16:42:02 +010028the very least, you have to call the function :c:func:`Py_Initialize`. There are
Georg Brandl9af94982008-09-13 17:41:16 +000029optional calls to pass command line arguments to Python. Then later you can
30call the interpreter from any part of the application.
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
32There are several different ways to call the interpreter: you can pass a string
Sandro Tosi98ed08f2012-01-14 16:42:02 +010033containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a
Georg Brandl8ec7f652007-08-15 14:28:01 +000034stdio file pointer and a file name (for identification in error messages only)
Sandro Tosi98ed08f2012-01-14 16:42:02 +010035to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations
Georg Brandl8ec7f652007-08-15 14:28:01 +000036described in the previous chapters to construct and use Python objects.
37
38A simple demo of embedding Python can be found in the directory
39:file:`Demo/embed/` of the source distribution.
40
41
42.. seealso::
43
44 :ref:`c-api-index`
45 The details of Python's C interface are given in this manual. A great deal of
46 necessary information can be found here.
47
48
49.. _high-level-embedding:
50
51Very High Level Embedding
52=========================
53
54The simplest form of embedding Python is the use of the very high level
55interface. This interface is intended to execute a Python script without needing
56to interact with the application directly. This can for example be used to
57perform some operation on a file. ::
58
59 #include <Python.h>
60
61 int
62 main(int argc, char *argv[])
63 {
Andrew Svetlov6e96e5e2012-10-31 16:01:09 +020064 Py_SetProgramName(argv[0]); /* optional but recommended */
Georg Brandl8ec7f652007-08-15 14:28:01 +000065 Py_Initialize();
66 PyRun_SimpleString("from time import time,ctime\n"
67 "print 'Today is',ctime(time())\n");
68 Py_Finalize();
69 return 0;
70 }
71
Andrew Svetlov6e96e5e2012-10-31 16:01:09 +020072Function :c:func:`Py_SetProgramName` should be called before
73:c:func:`Py_Initialize` to inform the interpreter about paths to
74Python run-time libraries. Next initialize the Python interpreter
75with :c:func:`Py_Initialize`, followed by the execution of a
76hard-coded Python script that prints the date and time. Afterwards,
77the :c:func:`Py_Finalize` call shuts the interpreter down, followed by
78the end of the program. In a real program, you may want to get the
79Python script from another source, perhaps a text-editor routine, a
80file, or a database. Getting the Python code from a file can better
81be done by using the :c:func:`PyRun_SimpleFile` function, which saves
82you the trouble of allocating memory space and loading the file
83contents.
Georg Brandl8ec7f652007-08-15 14:28:01 +000084
85
86.. _lower-level-embedding:
87
88Beyond Very High Level Embedding: An overview
89=============================================
90
91The high level interface gives you the ability to execute arbitrary pieces of
92Python code from your application, but exchanging data values is quite
93cumbersome to say the least. If you want that, you should use lower level calls.
94At the cost of having to write more C code, you can achieve almost anything.
95
96It should be noted that extending Python and embedding Python is quite the same
97activity, despite the different intent. Most topics discussed in the previous
98chapters are still valid. To show this, consider what the extension code from
99Python to C really does:
100
101#. Convert data values from Python to C,
102
103#. Perform a function call to a C routine using the converted values, and
104
105#. Convert the data values from the call from C to Python.
106
107When embedding Python, the interface code does:
108
109#. Convert data values from C to Python,
110
111#. Perform a function call to a Python interface routine using the converted
112 values, and
113
114#. Convert the data values from the call from Python to C.
115
116As you can see, the data conversion steps are simply swapped to accommodate the
117different direction of the cross-language transfer. The only difference is the
118routine that you call between both data conversions. When extending, you call a
119C routine, when embedding, you call a Python routine.
120
121This chapter will not discuss how to convert data from Python to C and vice
122versa. Also, proper use of references and dealing with errors is assumed to be
123understood. Since these aspects do not differ from extending the interpreter,
124you can refer to earlier chapters for the required information.
125
126
127.. _pure-embedding:
128
129Pure Embedding
130==============
131
132The first program aims to execute a function in a Python script. Like in the
133section about the very high level interface, the Python interpreter does not
134directly interact with the application (but that will change in the next
135section).
136
137The code to run a function defined in a Python script is:
138
139.. literalinclude:: ../includes/run-func.c
140
141
142This code loads a Python script using ``argv[1]``, and calls the function named
143in ``argv[2]``. Its integer arguments are the other values of the ``argv``
144array. If you compile and link this program (let's call the finished executable
145:program:`call`), and use it to execute a Python script, such as::
146
147 def multiply(a,b):
148 print "Will compute", a, "times", b
149 c = 0
150 for i in range(0, a):
151 c = c + b
152 return c
153
154then the result should be::
155
156 $ call multiply multiply 3 2
157 Will compute 3 times 2
158 Result of call: 6
159
160Although the program is quite large for its functionality, most of the code is
161for data conversion between Python and C, and for error reporting. The
Georg Brandlb19be572007-12-29 10:57:00 +0000162interesting part with respect to embedding Python starts with ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
164 Py_Initialize();
165 pName = PyString_FromString(argv[1]);
166 /* Error checking of pName left out */
167 pModule = PyImport_Import(pName);
168
169After initializing the interpreter, the script is loaded using
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100170:c:func:`PyImport_Import`. This routine needs a Python string as its argument,
171which is constructed using the :c:func:`PyString_FromString` data conversion
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172routine. ::
173
174 pFunc = PyObject_GetAttrString(pModule, argv[2]);
175 /* pFunc is a new reference */
176
177 if (pFunc && PyCallable_Check(pFunc)) {
178 ...
179 }
180 Py_XDECREF(pFunc);
181
182Once the script is loaded, the name we're looking for is retrieved using
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100183:c:func:`PyObject_GetAttrString`. If the name exists, and the object returned is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184callable, you can safely assume that it is a function. The program then
185proceeds by constructing a tuple of arguments as normal. The call to the Python
186function is then made with::
187
188 pValue = PyObject_CallObject(pFunc, pArgs);
189
190Upon return of the function, ``pValue`` is either *NULL* or it contains a
191reference to the return value of the function. Be sure to release the reference
192after examining the value.
193
194
195.. _extending-with-embedding:
196
197Extending Embedded Python
198=========================
199
200Until now, the embedded Python interpreter had no access to functionality from
201the application itself. The Python API allows this by extending the embedded
202interpreter. That is, the embedded interpreter gets extended with routines
203provided by the application. While it sounds complex, it is not so bad. Simply
204forget for a while that the application starts the Python interpreter. Instead,
205consider the application to be a set of subroutines, and write some glue code
206that gives Python access to those routines, just like you would write a normal
207Python extension. For example::
208
209 static int numargs=0;
210
211 /* Return the number of arguments of the application command line */
212 static PyObject*
213 emb_numargs(PyObject *self, PyObject *args)
214 {
215 if(!PyArg_ParseTuple(args, ":numargs"))
216 return NULL;
217 return Py_BuildValue("i", numargs);
218 }
219
220 static PyMethodDef EmbMethods[] = {
221 {"numargs", emb_numargs, METH_VARARGS,
222 "Return the number of arguments received by the process."},
223 {NULL, NULL, 0, NULL}
224 };
225
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100226Insert the above code just above the :c:func:`main` function. Also, insert the
227following two statements directly after :c:func:`Py_Initialize`::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
229 numargs = argc;
230 Py_InitModule("emb", EmbMethods);
231
232These two lines initialize the ``numargs`` variable, and make the
233:func:`emb.numargs` function accessible to the embedded Python interpreter.
234With these extensions, the Python script can do things like ::
235
236 import emb
237 print "Number of arguments", emb.numargs()
238
239In a real application, the methods will expose an API of the application to
240Python.
241
Georg Brandlb19be572007-12-29 10:57:00 +0000242.. TODO: threads, code examples do not really behave well if errors happen
243 (what to watch out for)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245
246.. _embeddingincplusplus:
247
248Embedding Python in C++
249=======================
250
251It is also possible to embed Python in a C++ program; precisely how this is done
252will depend on the details of the C++ system used; in general you will need to
253write the main program in C++, and use the C++ compiler to compile and link your
254program. There is no need to recompile Python itself using C++.
255
256
257.. _link-reqs:
258
259Linking Requirements
260====================
261
262While the :program:`configure` script shipped with the Python sources will
263correctly build Python to export the symbols needed by dynamically linked
264extensions, this is not automatically inherited by applications which embed the
265Python library statically, at least on Unix. This is an issue when the
266application is linked to the static runtime library (:file:`libpython.a`) and
267needs to load dynamic extensions (implemented as :file:`.so` files).
268
269The problem is that some entry points are defined by the Python runtime solely
270for extension modules to use. If the embedding application does not use any of
271these entry points, some linkers will not include those entries in the symbol
272table of the finished executable. Some additional options are needed to inform
273the linker not to remove these symbols.
274
275Determining the right options to use for any given platform can be quite
276difficult, but fortunately the Python configuration already has those values.
277To retrieve them from an installed Python interpreter, start an interactive
278interpreter and have a short session like this::
279
280 >>> import distutils.sysconfig
281 >>> distutils.sysconfig.get_config_var('LINKFORSHARED')
282 '-Xlinker -export-dynamic'
283
284.. index:: module: distutils.sysconfig
285
286The contents of the string presented will be the options that should be used.
287If the string is empty, there's no need to add any additional options. The
288:const:`LINKFORSHARED` definition corresponds to the variable of the same name
289in Python's top-level :file:`Makefile`.
290