首页 > 解决方案 > 二进制共享库到字符串并返回

问题描述

我想将我的共享库保存为 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. 所以编码肯定有问题。

标签: pythonpython-3.x

解决方案


就目前而言,二进制到引用打印步骤可以丢弃或破坏值为 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 更紧凑。


推荐阅读