在可执行文件中嵌入和访问二进制数据
- 来源: https://www.freebasic.net/wiki/wikka.php?wakka=ProPgDataExecutable
- 最后更新: 2021-10-21
如何在编译时将二进制数据嵌入可执行文件,并从程序代码中访问这些数据。
(基于 caseih 和 coderJeff 的论坛帖子)
本文介绍了一种将二进制数据包含在已编译程序中的方法,以及如何访问这些数据。
原理
FreeBASIC 发行版中包含的 (G)LD 链接器可以处理文件中的二进制数据,将其转换为目标文件。该目标文件导出的符号可以从程序代码中访问以读取数据。
链接器将根据提供的文件名构建两个字节符号:
一个用于数据块起始位置的符号(第一个数据字节),
另一个用于数据块结束位置的符号(最后一个数据字节之后的位置)。
通过将用户程序与目标文件一起编译,这两个字节符号的地址允许获取指向数据起始和结束位置的指针。
注意:将此原理应用于音频数据文件可能很有优势,例如,可以将音频数据包含在可执行文件中。音频数据起始位置的指针和音频数据的大小都可以传递给任何音频播放函数。
示例
简单示例,仅用于演示该原理(已在 linux/win 32/64 位 gas/gas64/gcc 上测试)。
本示例使用插入到 hello.txt 文本文件中的文本 ASCII 码字节作为二进制数据:
hello.txt 文本文件示例:
Hello!
Welcome to the forum.手动调用 LD 链接器,将 hello.txt 文本文件转换为导出符号的 hello.o 目标文件:
...\ld -r -b binary -o hello.o hello.txt
从 hello.o 目标文件导出两个字节符号:
- 在 Windows 32 位上:
binary_hello_txt_start:数据块的起始位置(第一个数据字节)
binary_hello_txt_end:数据块的结束位置(最后一个数据字节之后)
- 其他情况:
_binary_hello_txt_start:数据块的起始位置(第一个数据字节)
_binary_hello_txt_end:数据块的结束位置(最后一个数据字节之后)
在编译以下程序时,在命令行中包含 hello.o 目标文件(该程序打印嵌入在可执行文件中的 ASCII 码字节):
start GeSHi
Extern "C"
#if defined(__FB_WIN32__) And Not defined(__FB_64BIT__)
Extern hello_txt_start Alias "binary_hello_txt_start" As Const Byte
Extern hello_txt_end Alias "binary_hello_txt_end" As Const Byte
#else
Extern hello_txt_start Alias "_binary_hello_txt_start" As Const Byte
Extern hello_txt_end Alias "_binary_hello_txt_end" As Const Byte
#endif
End Extern
Dim hello_ptr As Const Byte Const Ptr = @hello_txt_start
Dim hello_length As Const UInteger = @hello_txt_end - @hello_txt_start
For i As UInteger = 0 To hello_length - 1
Print Chr(hello_ptr[i]);
Next
Print
Sleepend GeSHi
另请参阅
返回 目录