python - 二进制共享库到字符串并返回
问题描述
我想将我的共享库保存为 Python 文件中的字符串。为此,构建以下管道用于测试目的。首先,我将共享库加载到 Python 中,将其转换为字符串并保存。文本文件中的字符串可以作为字符串嵌入到某些 python 模块中。
import binascii
with open('start/mymodule.so', mode='rb') as file:
fileContent_binary1 = file.read()
fileContent_string = binascii.b2a_qp(fileContent_binary1).decode('utf-8')
with open('start/mymodule.txt', mode='w') as handle:
handle.write(fileContent_string)
现在我想获取字符串,将其转回二进制和可执行模块:
with open('start/mymodule.txt', mode='r') as file:
fileContent_string = file.read()
fileContent_binary2 = binascii.a2b_qp(fileContent_string.encode('utf-8'))
with open('end/mymodule.so', mode='wb') as handle:
handle.write(fileContent_binary2)
但是当我现在尝试导入新的mymodule.so
时,我得到了
进程以退出代码 139 结束(被信号 11 中断:SIGSEGV)
当我不保存字符串时也会发生这种情况,而是直接将二进制文件转换为字符串并返回并将其另存为mymodule.so
. 所以编码肯定有问题。
解决方案
就目前而言,二进制到引用打印步骤可以丢弃或破坏值为 0x0D(ASCII 回车符)的字节,因为默认情况下b2a_qp
认为其输入是文本并对其应用特殊的行尾处理。这种特殊处理可能会导致 0x0D 字节被丢弃和/或 0x0A(换行)字节被插入到结果中。
要修复,istext=False
请在调用中添加一个参数binascii.b2a_qp
。也就是说,改变这个:
fileContent_string = binascii.b2a_qp(fileContent_binary1).decode('utf-8')
对此:
fileContent_string = binascii.b2a_qp(fileContent_binary1, istext=False).decode('utf-8')
这b2a_qp
表明它正在对二进制文件进行编码,并且它不能丢弃或替换任何字节。
顺便说一句,您使用quoted-printable 作为中间文本格式是否有原因?Base64 是我的选择,主要是因为中间文件可能比 qp 更紧凑。
推荐阅读
- c++ - 在 C++ 中收到输入时如何停止执行异步函数
- android - 如何在 MediaCodec 中为 h264 创建编解码器特定数据 ( csd )?
- sql - 如果连接表没有行,则更新表
- react-native - 更新android studio后无法让Android模拟器运行应用程序
- apache-spark - 如何导入日常文件并在数据块中运行它们?
- java - 我可以在 Java 的控制台输出中打印黄瓜数据表吗?
- html - 多张图片的页面加载时间
- django - 为什么 widthratio(乘法)在我的模板中不起作用?
- javascript - 分配给变量的数组是“未定义的”
- javascript - 如何在 Angular 上为 ag-Grid 监听 sortChange(event)?