将 .exe 文件嵌入到 C++ 程序中?

Embed .exe file into C++ program?

我写了一个c++程序,我想在里面执行我的第二个程序,它是一个exe文件。问题是我想把我的程序作为一个文件分享给其他人。

当我在网上搜索时,我找到了这个解决方案。

Just store the second .exe file as a binary resource inside the main .exe using an .rc file at compile-time. At run-time, you can access it using FindResource(), LoadResource(), and LockResource(), and then write it out to a temp file on disk before passing it to system().

但是我不明白如何"store the .exe file as a binary resource"

我目前正在使用 CreateProcess() 启动我的第二个程序,它运行良好。 任何人都可以为我写一些例子吗?

在您项目的资源脚本(定义图标、对话框等的 .rc 文件)中,您可以使用如下行添加二进制资源:

IDB_EMBEDEXE    BINARY      "<path>\EmbedProgram.exe"

其中 IDB_EMBEDEXE token/macro 应在 both 包含的头文件中定义,该资源脚本 and 任何使用它的 C++ 源代码;这将是给 FindResource() 调用的 lpName 参数,您可以使用 MAKEINTRESOURCE(IDB_EMBEDEXE) 形成它。为 lpType 参数指定 "BINARY"(或 L"BINARY" 用于 Unicode 构建)。

像这样:

#define IDB_EMBEDEXE 13232 // Or whatever suitable value you need
//...
// In the C++ code:
HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), _TEXT("BINARY"));
HGLOBAL hGlobal = LoadResource(NULL, hResource);
size_t exeSiz = SizeofResource(NULL, hResource); // Size of the embedded data
void*  exeBuf = LockResource(hGlobal);           // usable pointer to that data

// You can now write the buffer to disk using "exeBuf" and "exeSiz"

指定的可执行文件将完全嵌入(作为二进制)资源到您的 built 可执行文件中,并且可以提取、写入磁盘并按照文章中的描述执行你引用。