背景:
ubuntu ,使用cpp调用python代码时,报错
Traceback (most recent call last):
File "/api.py", line 3, in <module>
import torch
File "/usr/local/lib/python3.8/dist-packages/torch/__init__.py", line 17, in <module>
import ctypes
File "/usr/lib/python3.8/ctypes/__init__.py", line 7, in <module>
from _ctypes import Union, Structure, Array
ImportError: /usr/lib/python3.8/lib-dynload/_ctypes.cpython-38-x86_64-linux-gnu.so: undefined symbol: PyFloat_Type
步骤:
1. 确保安装_ctypes
1.1 启动python终端
1.2 导入相应的模块
1.3 导入类
1.4 验证是否导入
python3
Python 3.8.10 (default, May 26 2023, 14:05:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes # 导入 ctypes 模块
>>> from _ctypes import Union, Structure, Array # 导入报错的类
>>> print(Union) # 验证是否导入成功
<class '_ctypes.Union'>
>>> print(Structure)
<class '_ctypes.Structure'>
>>> print(Array)
<class '_ctypes.Array'>
>>>
2. 截至到这里如果正常,那么意味着环境中python正常带有ctypes模块
因此参考 参考链接 :
PyFloat_Type should be defined in libpython. It would seem _struct.cpython-38-x86_64-linux-gnu.so does not depend on libpython so libpython will need to be loaded into the global namespace. By default JNI will load libpython in a local namespace. Try setting LD_PRELOAD to the location of your libpython so, to force it to be loaded globally.
虽然报错有些差异,但是大体相同。意思就是PyFloat_Type类型在libpython中定义,但是xxx.cpython库并不依赖libpython。所以需要将libpython库路径添加到指定环境变量来解决
export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libpython3.8.so