将二进制文件作为目标文件中的一个段
python 生成2进制文件
import sys
def testFile(fileName):
# --
with open(fileName, mode='wb+') as hexFile:
bBuf = bytes.fromhex("0123456789abcdef")
print("bBuf:",bBuf.hex())
len = hexFile.write(bBuf)
print ("len:",len)
test = ("my test code").encode()
hexFile.write(test)
with open(fileName, mode='rb') as hexFile:
bBuf = hexFile.read()
hexCode=bBuf[0:8]
print("hexCode:",hexCode.hex())
strBuf = bBuf[8:]
print("strBuf:",strBuf.decode())
pass
if __name__ == "__main__":
try:
testFile("tf.bin")
except Exception as e:
print(e)
pass
生成 tf.bin :
写入16进制数据0123456789abcdef
写入字符串my test code
使用编译工具链生成目标文件
- 我这使用 Qt -mingw-64 工具链:
打开powershell 输入命令配置临时环境变量:
$env:Path = "C:\Qt\Qt5.12.12\Tools\mingw730_64\bin;" + $env:Path
使用 tf.bin 生成目标 tf.o
objcopy.exe -I binary -O pe-x86-64 -B i386:x86-64 tf.bin tf.o
-I
指定源文件的格式
-O
指定输出的目标文件的格式
-B
指定输出目标文件的架构
查看效果:
PS D:\workspace\Python\PySwigLib> objdump -st tf.o
tf.o: file format pe-x86-64
SYMBOL TABLE:
[ 0](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000000 _binary_tf_bin_start
[ 1](sec 1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000014 _binary_tf_bin_end
[ 2](sec -1)(fl 0x00)(ty 0)(scl 2) (nx 0) 0x0000000000000014 _binary_tf_bin_size
用vscode 插件 Hex Editor 查看
用 c代码测试
testfile.c
#include "stdio.h"
extern __int64 _binary_tf_bin_start;
extern __int64 _binary_tf_bin_end;
extern __int64 _binary_tf_bin_size;
int main(int argc, char *argv[])
{
int index = 0;
char * start = (char *)&_binary_tf_bin_start;
char * end = (char *)&_binary_tf_bin_end;
__int64* size = (&_binary_tf_bin_size);
printf("_binary_tf_bin_start:0x%x\n",start);
printf("_binary_tf_bin_end:0x%x\n",end);
printf("_binary_tf_bin_size:0x%x\n",size);
while (start < end) {
printf("index %d :%02x\n", index, 0xff&(*start));
start++;
index++;
}
printf("size: %d\n", size);
return 0;
}
编译生成 可执行文件test.exe
gcc.exe .\testfile.c tf.o -o test.exe
运行:
PS D:\workspace\Python\PySwigLib> .\test.exe
_binary_tf_bin_start:0x403010
_binary_tf_bin_end:0x403024
_binary_tf_bin_size:0x14
index 0 :01
index 1 :23
index 2 :45
index 3 :67
index 4 :89
index 5 :ab
index 6 :cd
index 7 :ef
index 8 :6d
index 9 :79
index 10 :20
index 11 :74
index 12 :65
index 13 :73
index 14 :74
index 15 :20
index 16 :63
index 17 :6f
index 18 :64
index 19 :65
size: 20
可见写入的bin数据,连接生成 test.exe 之后,可以通过符号
_binary_tf_bin_start
_binary_tf_bin_end
_binary_tf_bin_size
获取其内容
tf.o 生成 tf.dll 动态库
ld tf.o -o tf.dll
链接动态库使用:
gcc.exe .\testfile.c tf.dll -o ./test.exe