Android平台Python调用.so共享对象出现dlopen失败问题求助
问题描述
我制作了一个共享对象,在Android的QPython 3.6.6中通过ctypes调用时出现dlopen失败错误;在Pydroid 3中也遇到类似的“library is not accessible for the namespace "(default)"”错误。该Python代码在Windows系统中调用dll可正常运行。
错误日志
/data/user/0/org.qpython.qpy3/files/bin/qpython3-android5.sh /storage/emulated/0/qpython/scripts3/.last_tmp.py && exit thon/scripts3/.last_tmp.py && exit Traceback (most recent call last): File "/storage/emulated/0/qpython/scripts3/.last_tmp.py", line 6, in <module> current_working_directory+"/scripts3/libsquare_dll.so") File "/data/user/0/org.qpython.qpy3/files/lib/python36.zip/ctypes/__init__.py", line 426, in LoadLibrary File "/data/user/0/org.qpython.qpy3/files/lib/python36.zip/ctypes/__init__.py", line 348, in __init__ OSError: dlopen failed: library "/storage/emulated/0/qpython/scripts3/libsquare_dll.so" needed or dlopened by "/data/user/0/org.qpython.qpy3/files/lib/python3.6/lib-dynload/_ctypes.cpython-36m.so" is not accessible for the namespace "(default)"
共享对象C代码
#include <stdint.h> #include "pch.h" extern "C" { void mysquare(uint64_t n, uint64_t* result) { *result = n * n; } }
Python调用代码
import ctypes from os import getcwd current_working_directory = getcwd() squaredll = ctypes.cdll.LoadLibrary ( current_working_directory+"/scripts3/libsquare_dll.so") square_dll = squaredll.mysquare res = ctypes.c_ulonglong() for n in range(10): square_dll(n, ctypes.byref(res) ) s = res.value print(n, s )
解决方案
这个错误由Android的命名空间隔离机制导致,QPython、Pydroid这类应用运行在沙箱环境中,无法直接访问外部存储(如/storage/emulated/0)中的共享库文件。
解决步骤:
- 将
libsquare_dll.so移动到Python应用的内部私有存储目录,比如QPython的/data/user/0/org.qpython.qpy3/files/libs/(需先创建libs子目录) - 修改Python代码中的库路径,指向内部存储的位置:
# QPython示例路径 squaredll = ctypes.cdll.LoadLibrary("/data/user/0/org.qpython.qpy3/files/libs/libsquare_dll.so") - 验证共享库的ABI架构与Android设备匹配(比如arm64-v8a、armeabi-v7a),避免因架构不兼容导致加载失败
额外注意事项:
- 不要依赖
getcwd()获取路径,Android沙箱中当前工作目录可能并非预期的外部存储路径 - 确保共享库没有依赖Android环境中不存在的系统库
内容的提问来源于stack exchange,提问作者Arthur Vause
相关产品推荐
相关产品推荐

