blob: 852e35f8b54ebe770020ef3132f2e99ff86c2f87 [file] [log] [blame]
Georg Brandld7413152009-10-11 21:25:26 +00001=======================
2Extending/Embedding FAQ
3=======================
4
Georg Brandl44ea77b2013-03-28 13:28:44 +01005.. only:: html
6
7 .. contents::
Georg Brandld7413152009-10-11 21:25:26 +00008
9.. highlight:: c
10
11
Georg Brandl62423cb2009-12-19 17:59:59 +000012.. XXX need review for Python 3.
13
14
Georg Brandld7413152009-10-11 21:25:26 +000015Can I create my own functions in C?
16-----------------------------------
17
18Yes, you can create built-in modules containing functions, variables, exceptions
19and even new types in C. This is explained in the document
20:ref:`extending-index`.
21
22Most intermediate or advanced Python books will also cover this topic.
23
24
25Can I create my own functions in C++?
26-------------------------------------
27
28Yes, using the C compatibility features found in C++. Place ``extern "C" {
29... }`` around the Python include files and put ``extern "C"`` before each
30function that is going to be called by the Python interpreter. Global or static
31C++ objects with constructors are probably not a good idea.
32
33
Georg Brandl4abda542010-07-12 09:00:29 +000034.. _c-wrapper-software:
35
Georg Brandld7413152009-10-11 21:25:26 +000036Writing C is hard; are there any alternatives?
37----------------------------------------------
38
39There are a number of alternatives to writing your own C extensions, depending
40on what you're trying to do.
41
Antoine Pitrou9cb41df2011-12-03 21:21:36 +010042.. XXX make sure these all work
Georg Brandld7413152009-10-11 21:25:26 +000043
Antoine Pitrou09264b62011-02-05 10:57:17 +000044`Cython <http://cython.org>`_ and its relative `Pyrex
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030045<https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_ are compilers
Antoine Pitrou09264b62011-02-05 10:57:17 +000046that accept a slightly modified form of Python and generate the corresponding
47C code. Cython and Pyrex make it possible to write an extension without having
48to learn Python's C API.
Georg Brandld7413152009-10-11 21:25:26 +000049
50If you need to interface to some C or C++ library for which no Python extension
51currently exists, you can try wrapping the library's data types and functions
52with a tool such as `SWIG <http://www.swig.org>`_. `SIP
Georg Brandl5d941342016-02-26 19:37:12 +010053<https://riverbankcomputing.com/software/sip/intro>`__, `CXX
Georg Brandld7413152009-10-11 21:25:26 +000054<http://cxx.sourceforge.net/>`_ `Boost
55<http://www.boost.org/libs/python/doc/index.html>`_, or `Weave
Georg Brandl5d941342016-02-26 19:37:12 +010056<https://scipy.github.io/devdocs/tutorial/weave.html>`_ are also
Georg Brandl77fe77d2014-10-29 09:24:54 +010057alternatives for wrapping C++ libraries.
Georg Brandld7413152009-10-11 21:25:26 +000058
59
60How can I execute arbitrary Python statements from C?
61-----------------------------------------------------
62
Georg Brandl60203b42010-10-06 10:11:56 +000063The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes
Georg Brandld7413152009-10-11 21:25:26 +000064a single string argument to be executed in the context of the module
65``__main__`` and returns 0 for success and -1 when an exception occurred
66(including ``SyntaxError``). If you want more control, use
Georg Brandl60203b42010-10-06 10:11:56 +000067:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in
Georg Brandld7413152009-10-11 21:25:26 +000068``Python/pythonrun.c``.
69
70
71How can I evaluate an arbitrary Python expression from C?
72---------------------------------------------------------
73
Georg Brandl60203b42010-10-06 10:11:56 +000074Call the function :c:func:`PyRun_String` from the previous question with the
75start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and
Georg Brandld7413152009-10-11 21:25:26 +000076returns its value.
77
78
79How do I extract C values from a Python object?
80-----------------------------------------------
81
Georg Brandl60203b42010-10-06 10:11:56 +000082That depends on the object's type. If it's a tuple, :c:func:`PyTuple_Size`
83returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified
84index. Lists have similar functions, :c:func:`PyListSize` and
85:c:func:`PyList_GetItem`.
Georg Brandld7413152009-10-11 21:25:26 +000086
Gregory P. Smith4b52ae82013-03-22 13:43:30 -070087For bytes, :c:func:`PyBytes_Size` returns its length and
88:c:func:`PyBytes_AsStringAndSize` provides a pointer to its value and its
89length. Note that Python bytes objects may contain null bytes so C's
90:c:func:`strlen` should not be used.
Georg Brandld7413152009-10-11 21:25:26 +000091
92To test the type of an object, first make sure it isn't *NULL*, and then use
Gregory P. Smith4b52ae82013-03-22 13:43:30 -070093:c:func:`PyBytes_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc.
Georg Brandld7413152009-10-11 21:25:26 +000094
95There is also a high-level API to Python objects which is provided by the
96so-called 'abstract' interface -- read ``Include/abstract.h`` for further
97details. It allows interfacing with any kind of Python sequence using calls
Zachary Ware2f31b4b2014-03-20 10:16:09 -050098like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc. as well
99as many other useful protocols such as numbers (:c:func:`PyNumber_Index` et
Gregory P. Smith4b52ae82013-03-22 13:43:30 -0700100al.) and mappings in the PyMapping APIs.
Georg Brandld7413152009-10-11 21:25:26 +0000101
102
103How do I use Py_BuildValue() to create a tuple of arbitrary length?
104-------------------------------------------------------------------
105
Antoine Pitrou48383bf2011-12-03 22:30:19 +0100106You can't. Use :c:func:`PyTuple_Pack` instead.
Georg Brandld7413152009-10-11 21:25:26 +0000107
108
109How do I call an object's method from C?
110----------------------------------------
111
Georg Brandl60203b42010-10-06 10:11:56 +0000112The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary
Georg Brandld7413152009-10-11 21:25:26 +0000113method of an object. The parameters are the object, the name of the method to
Georg Brandl60203b42010-10-06 10:11:56 +0000114call, a format string like that used with :c:func:`Py_BuildValue`, and the
Georg Brandld7413152009-10-11 21:25:26 +0000115argument values::
116
117 PyObject *
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300118 PyObject_CallMethod(PyObject *object, const char *method_name,
119 const char *arg_format, ...);
Georg Brandld7413152009-10-11 21:25:26 +0000120
121This works for any object that has methods -- whether built-in or user-defined.
Georg Brandl60203b42010-10-06 10:11:56 +0000122You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value.
Georg Brandld7413152009-10-11 21:25:26 +0000123
124To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the
125file object pointer is "f")::
126
127 res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
128 if (res == NULL) {
129 ... an exception occurred ...
130 }
131 else {
132 Py_DECREF(res);
133 }
134
Georg Brandl60203b42010-10-06 10:11:56 +0000135Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the
Georg Brandld7413152009-10-11 21:25:26 +0000136argument list, to call a function without arguments, pass "()" for the format,
137and to call a function with one argument, surround the argument in parentheses,
138e.g. "(i)".
139
140
141How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?
142----------------------------------------------------------------------------------------
143
144In Python code, define an object that supports the ``write()`` method. Assign
145this object to :data:`sys.stdout` and :data:`sys.stderr`. Call print_error, or
146just allow the standard traceback mechanism to work. Then, the output will go
147wherever your ``write()`` method sends it.
148
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100149The easiest way to do this is to use the :class:`io.StringIO` class::
Georg Brandld7413152009-10-11 21:25:26 +0000150
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100151 >>> import io, sys
152 >>> sys.stdout = io.StringIO()
153 >>> print('foo')
154 >>> print('hello world!')
155 >>> sys.stderr.write(sys.stdout.getvalue())
156 foo
157 hello world!
Georg Brandld7413152009-10-11 21:25:26 +0000158
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100159A custom object to do the same would look like this::
160
161 >>> import io, sys
162 >>> class StdoutCatcher(io.TextIOBase):
Georg Brandld7413152009-10-11 21:25:26 +0000163 ... def __init__(self):
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100164 ... self.data = []
Georg Brandld7413152009-10-11 21:25:26 +0000165 ... def write(self, stuff):
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100166 ... self.data.append(stuff)
Georg Brandld7413152009-10-11 21:25:26 +0000167 ...
168 >>> import sys
169 >>> sys.stdout = StdoutCatcher()
Georg Brandl62423cb2009-12-19 17:59:59 +0000170 >>> print('foo')
171 >>> print('hello world!')
Antoine Pitroud4ddec52011-12-03 22:35:31 +0100172 >>> sys.stderr.write(''.join(sys.stdout.data))
Georg Brandld7413152009-10-11 21:25:26 +0000173 foo
174 hello world!
175
176
177How do I access a module written in Python from C?
178--------------------------------------------------
179
180You can get a pointer to the module object as follows::
181
182 module = PyImport_ImportModule("<modulename>");
183
184If the module hasn't been imported yet (i.e. it is not yet present in
185:data:`sys.modules`), this initializes the module; otherwise it simply returns
186the value of ``sys.modules["<modulename>"]``. Note that it doesn't enter the
187module into any namespace -- it only ensures it has been initialized and is
188stored in :data:`sys.modules`.
189
190You can then access the module's attributes (i.e. any name defined in the
191module) as follows::
192
193 attr = PyObject_GetAttrString(module, "<attrname>");
194
Georg Brandl60203b42010-10-06 10:11:56 +0000195Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module
Georg Brandld7413152009-10-11 21:25:26 +0000196also works.
197
198
199How do I interface to C++ objects from Python?
200----------------------------------------------
201
202Depending on your requirements, there are many approaches. To do this manually,
203begin by reading :ref:`the "Extending and Embedding" document
204<extending-index>`. Realize that for the Python run-time system, there isn't a
205whole lot of difference between C and C++ -- so the strategy of building a new
206Python type around a C structure (pointer) type will also work for C++ objects.
207
Georg Brandl4abda542010-07-12 09:00:29 +0000208For C++ libraries, see :ref:`c-wrapper-software`.
Georg Brandld7413152009-10-11 21:25:26 +0000209
210
211I added a module using the Setup file and the make fails; why?
212--------------------------------------------------------------
213
214Setup must end in a newline, if there is no newline there, the build process
215fails. (Fixing this requires some ugly shell script hackery, and this bug is so
216minor that it doesn't seem worth the effort.)
217
218
219How do I debug an extension?
220----------------------------
221
222When using GDB with dynamically loaded extensions, you can't set a breakpoint in
223your extension until your extension is loaded.
224
225In your ``.gdbinit`` file (or interactively), add the command::
226
227 br _PyImport_LoadDynamicModule
228
229Then, when you run GDB::
230
231 $ gdb /local/bin/python
232 gdb) run myscript.py
233 gdb) continue # repeat until your extension is loaded
234 gdb) finish # so that your extension is loaded
235 gdb) br myfunction.c:50
236 gdb) continue
237
238I want to compile a Python module on my Linux system, but some files are missing. Why?
239--------------------------------------------------------------------------------------
240
241Most packaged versions of Python don't include the
242:file:`/usr/lib/python2.{x}/config/` directory, which contains various files
243required for compiling Python extensions.
244
245For Red Hat, install the python-devel RPM to get the necessary files.
246
247For Debian, run ``apt-get install python-dev``.
248
249
Georg Brandld7413152009-10-11 21:25:26 +0000250How do I tell "incomplete input" from "invalid input"?
251------------------------------------------------------
252
253Sometimes you want to emulate the Python interactive interpreter's behavior,
254where it gives you a continuation prompt when the input is incomplete (e.g. you
255typed the start of an "if" statement or you didn't close your parentheses or
256triple string quotes), but it gives you a syntax error message immediately when
257the input is invalid.
258
259In Python you can use the :mod:`codeop` module, which approximates the parser's
260behavior sufficiently. IDLE uses this, for example.
261
Georg Brandl60203b42010-10-06 10:11:56 +0000262The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps
Georg Brandld7413152009-10-11 21:25:26 +0000263in a separate thread) and let the Python interpreter handle the input for
Georg Brandl60203b42010-10-06 10:11:56 +0000264you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your
Georg Brandld7413152009-10-11 21:25:26 +0000265custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c``
266for more hints.
267
268However sometimes you have to run the embedded Python interpreter in the same
269thread as your rest application and you can't allow the
Georg Brandl60203b42010-10-06 10:11:56 +0000270:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input. The one
271solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error``
Georg Brandld7413152009-10-11 21:25:26 +0000272equal to ``E_EOF``, which means the input is incomplete). Here's a sample code
273fragment, untested, inspired by code from Alex Farber::
274
275 #include <Python.h>
276 #include <node.h>
277 #include <errcode.h>
278 #include <grammar.h>
279 #include <parsetok.h>
280 #include <compile.h>
281
282 int testcomplete(char *code)
283 /* code should end in \n */
284 /* return -1 for error, 0 for incomplete, 1 for complete */
285 {
286 node *n;
287 perrdetail e;
288
289 n = PyParser_ParseString(code, &_PyParser_Grammar,
290 Py_file_input, &e);
291 if (n == NULL) {
292 if (e.error == E_EOF)
293 return 0;
294 return -1;
295 }
296
297 PyNode_Free(n);
298 return 1;
299 }
300
301Another solution is trying to compile the received string with
Georg Brandl60203b42010-10-06 10:11:56 +0000302:c:func:`Py_CompileString`. If it compiles without errors, try to execute the
303returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the
Georg Brandld7413152009-10-11 21:25:26 +0000304input for later. If the compilation fails, find out if it's an error or just
305more input is required - by extracting the message string from the exception
306tuple and comparing it to the string "unexpected EOF while parsing". Here is a
307complete example using the GNU readline library (you may want to ignore
308**SIGINT** while calling readline())::
309
310 #include <stdio.h>
311 #include <readline.h>
312
313 #include <Python.h>
314 #include <object.h>
315 #include <compile.h>
316 #include <eval.h>
317
318 int main (int argc, char* argv[])
319 {
320 int i, j, done = 0; /* lengths of line, code */
321 char ps1[] = ">>> ";
322 char ps2[] = "... ";
323 char *prompt = ps1;
324 char *msg, *line, *code = NULL;
325 PyObject *src, *glb, *loc;
326 PyObject *exc, *val, *trb, *obj, *dum;
327
328 Py_Initialize ();
329 loc = PyDict_New ();
330 glb = PyDict_New ();
331 PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());
332
333 while (!done)
334 {
335 line = readline (prompt);
336
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300337 if (NULL == line) /* Ctrl-D pressed */
Georg Brandld7413152009-10-11 21:25:26 +0000338 {
339 done = 1;
340 }
341 else
342 {
343 i = strlen (line);
344
345 if (i > 0)
346 add_history (line); /* save non-empty lines */
347
348 if (NULL == code) /* nothing in code yet */
349 j = 0;
350 else
351 j = strlen (code);
352
353 code = realloc (code, i + j + 2);
354 if (NULL == code) /* out of memory */
355 exit (1);
356
357 if (0 == j) /* code was empty, so */
358 code[0] = '\0'; /* keep strncat happy */
359
360 strncat (code, line, i); /* append line to code */
361 code[i + j] = '\n'; /* append '\n' to code */
362 code[i + j + 1] = '\0';
363
364 src = Py_CompileString (code, "<stdin>", Py_single_input);
365
366 if (NULL != src) /* compiled just fine - */
367 {
368 if (ps1 == prompt || /* ">>> " or */
369 '\n' == code[i + j - 1]) /* "... " and double '\n' */
370 { /* so execute it */
Martin v. Löwis4d0d4712010-12-03 20:14:31 +0000371 dum = PyEval_EvalCode (src, glb, loc);
Georg Brandld7413152009-10-11 21:25:26 +0000372 Py_XDECREF (dum);
373 Py_XDECREF (src);
374 free (code);
375 code = NULL;
376 if (PyErr_Occurred ())
377 PyErr_Print ();
378 prompt = ps1;
379 }
380 } /* syntax error or E_EOF? */
381 else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
382 {
383 PyErr_Fetch (&exc, &val, &trb); /* clears exception! */
384
385 if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
386 !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
387 {
388 Py_XDECREF (exc);
389 Py_XDECREF (val);
390 Py_XDECREF (trb);
391 prompt = ps2;
392 }
393 else /* some other syntax error */
394 {
395 PyErr_Restore (exc, val, trb);
396 PyErr_Print ();
397 free (code);
398 code = NULL;
399 prompt = ps1;
400 }
401 }
402 else /* some non-syntax error */
403 {
404 PyErr_Print ();
405 free (code);
406 code = NULL;
407 prompt = ps1;
408 }
409
410 free (line);
411 }
412 }
413
414 Py_XDECREF(glb);
415 Py_XDECREF(loc);
416 Py_Finalize();
417 exit(0);
418 }
419
420
421How do I find undefined g++ symbols __builtin_new or __pure_virtual?
422--------------------------------------------------------------------
423
424To dynamically load g++ extension modules, you must recompile Python, relink it
Ezio Melotti0639d5a2009-12-19 23:26:38 +0000425using g++ (change LINKCC in the Python Modules Makefile), and link your
Georg Brandld7413152009-10-11 21:25:26 +0000426extension module using g++ (e.g., ``g++ -shared -o mymodule.so mymodule.o``).
427
428
429Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?
430----------------------------------------------------------------------------------------------------------------
431
Benjamin Peterson0071b3d2015-10-10 23:23:55 -0700432Yes, you can inherit from built-in classes such as :class:`int`, :class:`list`,
433:class:`dict`, etc.
Georg Brandld7413152009-10-11 21:25:26 +0000434
435The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html)
436provides a way of doing this from C++ (i.e. you can inherit from an extension
437class written in C++ using the BPL).