| 1 |
|
| 2 |
############################# |
| 3 |
Python shared library problem |
| 4 |
############################# |
| 5 |
|
| 6 |
Problem: Native Python C-extensions can't find Python symbols if Python interpreter is embedded into a shared library. |
| 7 |
This problem does not occur on Windows systems. |
| 8 |
|
| 9 |
* mypydl.c - Source for a shared libary (mypydl.so) that embeds a Python interpreter |
| 10 |
* mypy.c - Source for a main program (mypy) that dynamically loads the shared library mypydl.so |
| 11 |
* mypymod.c - Native Python extension module (mypymod) that uses the Python C-API |
| 12 |
|
| 13 |
make.sh - builds mypydl.so, mypy and the mypymod Python extension module. |
| 14 |
|
| 15 |
The main program mypy interprets all given arguments as Python code and executes it:: |
| 16 |
|
| 17 |
$ bash ./make.sh |
| 18 |
$ ./mypy "print('Hello')" |
| 19 |
mypy: executing [print('Hello')] |
| 20 |
Hello |
| 21 |
mypy: status 0 |
| 22 |
|
| 23 |
Here is how to reproduce the problem:: |
| 24 |
|
| 25 |
$ ./mypy "import mypymod" |
| 26 |
mypy: executing [import mypymod] |
| 27 |
Traceback (most recent call last): |
| 28 |
File "<string>", line 1, in <module> |
| 29 |
ImportError: /home/norman/.local/lib/python3.4/site-packages/mypymod.cpython-34m.so: undefined symbol: Py_BuildValue |
| 30 |
... |
| 31 |
mypy: status -1 |
| 32 |
|
| 33 |
Or with numpy:: |
| 34 |
|
| 35 |
$ ./mypy "import numpy" |
| 36 |
mypy: executing [import numpy] |
| 37 |
... |
| 38 |
ImportError: /home/norman/.local/lib/python3.4/site-packages/numpy/core/multiarray.cpython-34m.so: undefined symbol: PyExc_SystemError |
| 39 |
mypy: status -1 |
| 40 |
|
| 41 |
|
| 42 |
If the Python shared library is explicitly pre-loaded, then these errors don't occur:: |
| 43 |
|
| 44 |
$ LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpython3.4m.so ./mypy "import mypymod" |
| 45 |
mypy: executing [import mypymod] |
| 46 |
PyInit_mypymod: enter |
| 47 |
PyInit_mypymod: exit: module=0x7f72d34a4188 |
| 48 |
mypy: status 0 |
| 49 |
|
| 50 |
The error also doesn't occur, if I link my Python extension module explicitly against the Python shared library:: |
| 51 |
|
| 52 |
extension = Extension('mypymod', sources=['mypymod.c'], libraries=['python3.4m']) |
| 53 |
setup(name='mypymod', ext_modules=[extension]) |
| 54 |
|
| 55 |
Understandably but unfortunately, most Python extensions don't declare the dependency to a specific Python version explicitly. |