Debian Codegraph @

pypy/doc/embedding.rst

raw
1 Embedding PyPy (DEPRECATED)
2 ===========================
3
4 PyPy has a very minimal and a very strange embedding interface, based on
5 the usage of `cffi`_ and the philosophy that Python is a better language than
6 C. It was developed in collaboration with Roberto De Ioris from the `uwsgi`_
7 project. The `PyPy uwsgi plugin`_ is a good example of using the embedding API.
8
9 **NOTE**: You need a PyPy compiled with the option ``--shared``, i.e.
10 with a ``libpypy*-c.so`` or ``pypy*-c.dll`` file. This is the default.
11
12 .. note::
13
14 The interface described in this page is kept for backward compatibility.
15 From PyPy 4.1, it is recommended to use instead CFFI's `native embedding
16 support,`__ which gives a simpler approach that works on CPython as well
17 as PyPy.
18
19 .. __: https://cffi.readthedocs.org/en/latest/embedding.html
20
21 The resulting shared library exports very few functions. These are defined in
22 ``PyPy.h`` which was removed in v7.3.8, but `is still available`_.
23 They are enough to accomplish everything you need, provided you follow a few
24 principles. The API is:
25
26 .. function:: void rpython_startup_code(void);
27
28 This is a function that you have to call (once) before calling anything else.
29 It initializes the RPython/PyPy GC and does a bunch of necessary startup
30 code. This function cannot fail.
31
32 .. function:: int pypy_setup_home(char* home, int verbose);
33
34 This function searches the PyPy standard library starting from the given
35 "PyPy home directory". The arguments are:
36
37 * ``home``: path to an executable inside the pypy directory
38 (can be a .so name, can be made up). Used to look up the standard
39 library, and is also set as ``sys.executable``. From PyPy 5.5, you can
40 just say NULL here, as long as the ``libpypy-c.so/dylib/dll`` is itself
41 inside this directory.
42
43 * ``verbose``: if non-zero, it will print error messages to stderr
44
45 Function returns 0 on success or -1 on failure, can be called multiple times
46 until the library is found.
47
48 .. function:: void pypy_init_threads(void);
49
50 Initialize threads. Only need to be called if there are any threads involved.
51 *Must be called after pypy_setup_home()*
52
53 .. function:: int pypy_execute_source(char* source);
54
55 Execute the Python source code given in the ``source`` argument. In case of
56 exceptions, it will print the Python traceback to stderr and return 1,
57 otherwise return 0. You should really do your own error handling in the
58 source. It'll acquire the GIL.
59
60 Note: this is meant to be called *only once* or a few times at most. See
61 the `more complete example`_ below. In PyPy <= 2.6.0, the globals
62 dictionary is *reused* across multiple calls, giving potentially
63 strange results (e.g. objects dying too early). In PyPy >= 2.6.1,
64 you get a new globals dictionary for every call (but then, all globals
65 dictionaries are all kept alive forever, in ``sys._pypy_execute_source``).
66
67 .. function:: int pypy_execute_source_ptr(char* source, void* ptr);
68
69 .. note:: added in PyPy 2.3.1, June 2014
70
71 Just like the above, except it registers a magic argument in the source
72 scope as ``c_argument``, where ``void*`` is encoded as Python int.
73
74 .. function:: void pypy_thread_attach(void);
75
76 In case your application uses threads that are initialized outside of PyPy,
77 you need to call this function to tell the PyPy GC to track this thread.
78 Note that this function is not thread-safe itself, so you need to guard it
79 with a mutex.
80
81
82 Minimal example
83 ---------------
84
85 Note that this API is a lot more minimal than say CPython C API, so at first
86 it's obvious to think that you can't do much. However, the trick is to do
87 all the logic in Python and expose it via `cffi`_ callbacks.
88 We write a little C program:
89
90 .. code-block:: c
91
92 #include "PyPy.h"
93 #include <stdio.h>
94 #include <stdlib.h>
95
96 static char source[] = "print 'hello from pypy'";
97
98 int main(void)
99 {
100 int res;
101
102 rpython_startup_code();
103 /* Before PyPy 5.5, you may need to say e.g. "/opt/pypy/bin" instead
104 * of NULL. */
105 res = pypy_setup_home(NULL, 1);
106 if (res) {
107 printf("Error setting pypy home!\n");
108 return 1;
109 }
110
111 res = pypy_execute_source((char*)source);
112 if (res) {
113 printf("Error calling pypy_execute_source!\n");
114 }
115 return res;
116 }
117
118 If we save it as ``x.c`` now, compile it and run it (on linux) with::
119
120 $ gcc -g -o x x.c -lpypy-c -L/opt/pypy/bin -I/opt/pypy/include
121 $ LD_LIBRARY_PATH=/opt/pypy/bin ./x
122 hello from pypy
123
124 On OSX it is necessary to set the rpath of the binary if one wants to link to it,
125 with a command like::
126
127 gcc -o x x.c -lpypy-c -L. -Wl,-rpath -Wl,@executable_path
128 ./x
129 hello from pypy
130
131
132 More complete example
133 ---------------------
134
135 .. note:: Note that we do not make use of ``extern "Python"``, the new
136 way to do callbacks in CFFI 1.4: this is because these examples use
137 the ABI mode, not the API mode, and with the ABI mode you still have
138 to use ``ffi.callback()``. It is work in progress to integrate
139 ``extern "Python"`` with the idea of embedding (and it is expected
140 to ultimately lead to a better way to do embedding than the one
141 described here, and that would work equally well on CPython and PyPy).
142
143 Typically we need something more to do than simply execute source. The following
144 is a fully fledged example, please consult cffi documentation for details.
145 It's a bit longish, but it captures a gist what can be done with the PyPy
146 embedding interface:
147
148 .. code-block:: python
149
150 # file "interface.py"
151
152 import cffi
153
154 ffi = cffi.FFI()
155 ffi.cdef('''
156 struct API {
157 double (*add_numbers)(double x, double y);
158 };
159 ''')
160
161 # Better define callbacks at module scope, it's important to
162 # keep this object alive.
163 @ffi.callback("double (double, double)")
164 def add_numbers(x, y):
165 return x + y
166
167 def fill_api(ptr):
168 global api
169 api = ffi.cast("struct API*", ptr)
170 api.add_numbers = add_numbers
171
172 .. code-block:: c
173
174 /* C example */
175 #include "PyPy.h"
176 #include <stdio.h>
177 #include <stdlib.h>
178
179 struct API {
180 double (*add_numbers)(double x, double y);
181 };
182
183 struct API api; /* global var */
184
185 int initialize_api(void)
186 {
187 static char source[] =
188 "import sys; sys.path.insert(0, '.'); "
189 "import interface; interface.fill_api(c_argument)";
190 int res;
191
192 rpython_startup_code();
193 res = pypy_setup_home(NULL, 1);
194 if (res) {
195 fprintf(stderr, "Error setting pypy home!\n");
196 return -1;
197 }
198 res = pypy_execute_source_ptr(source, &api);
199 if (res) {
200 fprintf(stderr, "Error calling pypy_execute_source_ptr!\n");
201 return -1;
202 }
203 return 0;
204 }
205
206 int main(void)
207 {
208 if (initialize_api() < 0)
209 return 1;
210
211 printf("sum: %f\n", api.add_numbers(12.3, 45.6));
212
213 return 0;
214 }
215
216 you can compile and run it with::
217
218 $ gcc -g -o x x.c -lpypy-c -L/opt/pypy/bin -I/opt/pypy/include
219 $ LD_LIBRARY_PATH=/opt/pypy/bin ./x
220 sum: 57.900000
221
222 As you can see, what we did is create a ``struct API`` that contains
223 the custom API that we need in our particular case. This struct is
224 filled by Python to contain a function pointer that is then called
225 form the C side. It is also possible to do have other function
226 pointers that are filled by the C side and called by the Python side,
227 or even non-function-pointer fields: basically, the two sides
228 communicate via this single C structure that defines your API.
229
230
231 Finding pypy_home
232 -----------------
233
234 **You can usually skip this section if you are running PyPy >= 5.5, released
235 Oct 2016**
236
237 The function pypy_setup_home() takes as first parameter the path to a
238 file from which it can deduce the location of the standard library.
239 More precisely, it tries to remove final components until it finds
240 ``lib-python`` and ``lib_pypy``. There is currently no "clean" way
241 (pkg-config comes to mind) to find this path. You can try the following
242 (GNU-specific) hack (don't forget to link against *dl*), which assumes
243 that the ``libpypy-c.so`` is inside the standard library directory.
244 (This must more-or-less be the case anyway, otherwise the ``pypy``
245 program itself would not run.)
246
247 .. code-block:: c
248
249 #if !(_GNU_SOURCE)
250 #define _GNU_SOURCE
251 #endif
252
253 #include <dlfcn.h>
254 #include <limits.h>
255 #include <stdlib.h>
256
257 // caller should free returned pointer to avoid memleaks
258 // returns NULL on error
259 char* guess_pypyhome(void) {
260 // glibc-only (dladdr is why we #define _GNU_SOURCE)
261 Dl_info info;
262 void *_rpython_startup_code = dlsym(0,"rpython_startup_code");
263 if (_rpython_startup_code == 0) {
264 return 0;
265 }
266 if (dladdr(_rpython_startup_code, &info) != 0) {
267 const char* lib_path = info.dli_fname;
268 char* lib_realpath = realpath(lib_path, 0);
269 return lib_realpath;
270 }
271 return 0;
272 }
273
274
275 Threading
276 ---------
277
278 In case you want to use pthreads, what you need to do is to call
279 ``pypy_thread_attach`` from each of the threads that you created (but not
280 from the main thread) and call ``pypy_init_threads`` from the main thread.
281
282 .. _`cffi`: https://cffi.readthedocs.org/
283 .. _`uwsgi`: https://uwsgi-docs.readthedocs.org/en/latest/
284 .. _`PyPy uwsgi plugin`: https://uwsgi-docs.readthedocs.org/en/latest/PyPy.html
285 .. _`how to compile PyPy`: getting-started.html
286 .. _`is still available`: pypy.h.html