You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinAPI UpdateResource修改PyInstaller生成EXE资源致程序损坏求助

PyInstaller生成的EXE修改资源后损坏问题

我用PyInstaller将Python脚本打包成EXE文件,之后通过Resource Hacker为该EXE添加了一个文本文件作为资源。尝试用WinAPI的UpdateResource函数编程修改这个资源文本时,操作返回成功,但EXE文件直接损坏——大小从75MB骤减至271KB,运行时提示*“Cannot open PyInstaller from executable”*错误。

我分别用Python和C++实现了修改逻辑,均无法解决问题。以下是使用的代码:

Python代码

exe_file = r"\path\to\exe_file.exe"
handle = win32api.BeginUpdateResource(exe_file, False)
resource_type = win32con.RT_RCDATA
new_data = "modified text".encode()
try:
    win32api.UpdateResource(handle, resource_type, 110, new_data)

    # 保存修改并关闭文件
    win32api.EndUpdateResource(handle, False)
except:
    win32api.EndUpdateResource(handle, True)

C++代码(简化版,实际已处理句柄无效情况)

#include <windows.h>
#include <winbase.h>
#include <winuser.h>


int modify_resource(const LPCWSTR new_text, const LPCWSTR filename)
{
    const LPCWSTR res_type = MAKEINTRESOURCE(RT_RCDATA);
    const LPCWSTR res_name = MAKEINTRESOURCE(110); // 资源ID

    HMODULE module = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
    HRSRC res_info = FindResource(module, res_name, res_type);

    DWORD res_size = SizeofResource(module, res_info);
    HGLOBAL res_data = LoadResource(module, res_info);

    LPVOID res_ptr = LockResource(res_data);
    FreeResource(res_data);
    HANDLE update_handle = BeginUpdateResource(filename, FALSE);

    BOOL result = UpdateResource(update_handle, res_type, res_name, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (LPVOID)new_text, (DWORD)(wcslen(new_text) + 1) * sizeof(wchar_t));
    if (!result)
    {
        EndUpdateResource(update_handle, TRUE);
        FreeLibrary(module);
        return 1;
    }

    result = EndUpdateResource(update_handle, FALSE);
    FreeLibrary(module);
    if (!result)
    {
        return 1;
    }
    return 0;
}

编辑补充:最小化复现步骤

  • 将以下Python脚本转换为EXE:
input("Press enter to exit")

使用PyInstaller命令:pyinstaller --onefile --console <script_name.py>

  • 运行以下C++代码:
#include <windows.h>
#define RES_ID 110

int main();
{
    const LPCWSTR res_type = MAKEINTRESOURCE(RT_RCDATA);
    const LPCWSTR res_name = MAKEINTRESOURCE(RES_ID);
    HMODULE module = LoadLibrary(L"exe\\to\\copy\\resource\\from.exe");
    HRSRC res_info = FindResource(module, res_name, res_type);
    HGLOBAL res_load = LoadResource(module, res_info);
    LPVOID res_ptr = LockResource(res_load);

    HANDLE update_handle = BeginUpdateResource(L"path\\to\\python\\exe.exe", FALSE);
    DWORD res_size = SizeofResource(module, res_info);

    BOOL result = UpdateResource(update_handle,
        res_type,
        res_name,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
        res_ptr,
        res_size);

    EndUpdateResource(update_handle, FALSE);
    FreeLibrary(module);
    return 0;
}

内容的提问来源于stack exchange,提问作者Roey_MR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:52:52