在c++中编译一个exe文件

Compile an exe file inside c++

本文关键字:一个 exe 文件 c++ 编译      更新时间:2023-10-16

我想创建一个c++程序,其中

  1. 我可以读取外部文件(可以是exe,dll,apk…等…等)。也就是读取文件将它们转换成字节并存储在数组

  2. 接下来,我要编译数组内的字节现在这是比较棘手的部分我想把字节编译成一个数组来检查字节是否工作正常

  3. 您可能会说我正在将文件转换为字节,然后将这些字节转换回相同的文件....(是的,我确实是这样做的)

这可能吗?

测试可执行文件是否可以加载(与执行不完全相同):

  • 它将成功,除非
    • 缺少权限
    • 文件不可访问
    • 其中一个依赖项不可访问(例如依赖库)

请注意,在UNIX上,同样可以使用dlopen

来实现。

.

// A simple program that uses LoadLibrary
#include <windows.h> 
#include <stdio.h> 
int main( void ) 
{ 
    HINSTANCE hinstLib; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 
    // Get a handle to the DLL module.
    hinstLib = LoadLibrary(TEXT("input.exe"));  // or dll
    fFreeResult = FreeLibrary(hinstLib); 
if (hinstLib != NULL)
        printf("Message printed from executablen"); 
    return 0;
}

参见

    <
  • LoadLibrary函数/gh><
  • LoadLibraryEx函数/gh>

使用流复制

#include <sstream>
#include <fstream>
int main()
{
    std::stringstream in_memory(
            std::ios_base::out | 
            std::ios_base::in | 
            std::ios::binary);
    {   
        // reading whole file into memory
        std::ifstream ifs("input.exe", std::ios::in | std::ios::binary);
        in_memory << ifs.rdbuf();
    }
    {
        // optionally write it out
        std::ofstream ofs("input.exe.copy", std::ios::out | std::ios::binary);
        ofs << in_memory.rdbuf();
    }
    return 0;
}

如果你不使用内存阶段,它会更有效率(非常大的文件不会引起问题):

#include <sstream>
#include <fstream>
int main()
{
    std::ofstream("input.exe.copy2", std::ios::out | std::ios::binary)
        << std::ifstream("input.exe", std::ios::in | std::ios::binary).rdbuf();
    return 0;
}