自动更新 DLL 组件 — 使用 C++ / CMake / vcpkg 构建。
仓库: szWrn/auto-update
English version
auto_update.dll— 动态链接库
| 函数 | 说明 |
|---|---|
setUpdateListsUrl(url) |
设置 updateLists.json 的获取地址(硬编码于宿主程序)。getUpdateInfo 之前必须调用 |
setCurrentVersion(ver) |
传入宿主程序的当前版本号(如 "1.0.0")。getUpdateInfo 之前必须调用 |
getUpdateInfo(info) |
获取远程更新信息,比较版本号,探测所有镜像延迟,选出最快的下载地址 |
update(url) |
下载更新程序到临时目录并启动它 |
当前版本号由宿主程序通过 setCurrentVersion 传入,仅在内存中持有,不读取任何外部文件。这防止了用户通过篡改本地 version.json 绕过更新检查。
远端 updateLists.json 的 URL 同样硬编码在宿主程序中,由 setUpdateListsUrl 传入。
getUpdateInfo: 1 = 有更新 | 0 = 已是最新 | -1 = 错误update: 1 = 成功 | 0 = 失败
#include "auto_update.h"
// 1. 配置(程序启动时调用一次)
setUpdateListsUrl("https://your-server.com/updateLists.json");
setCurrentVersion("1.0.0"); // 编译期硬编码的版本号,防止篡改
// 2. 检查更新
UpdateInfo info;
int ret = getUpdateInfo(&info);
if (ret == 1) {
// info.priority: "silent" | "warn" | "force"
if (strcmp(info.priority, "silent") == 0) {
update(info.bestUrl); // 静默更新
} else if (strcmp(info.priority, "warn") == 0) {
if (MessageBox(..., MB_OKCANCEL) == IDOK) update(info.bestUrl);
} else { // "force"
if (MessageBox(..., MB_OKCANCEL) == IDCANCEL) exit(0);
update(info.bestUrl);
}
}- libcurl — HTTP 请求
- nlohmann-json — JSON 解析
通过 vcpkg manifest 模式管理,构建时自动安装。
- 安装 vcpkg
- 设置环境变量
VCPKG_ROOT指向 vcpkg 安装目录
.\build.ps1 # Release(默认)
.\build.ps1 -Debug # Debug 构建
.\build.ps1 -Clean # 清理后重新构建产物位于 build/Release/auto_update.dll。
cmake -B build -S . \
-DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake"
cmake --build build --config Release在 settings.json 中添加:
{
"cmake.configureArgs": [
"-DCMAKE_TOOLCHAIN_FILE=<VCPKG_ROOT>/scripts/buildsystems/vcpkg.cmake"
]
}auto_update/
├── CMakeLists.txt # 构建配置
├── vcpkg.json # 依赖声明
├── include/
│ └── auto_update.h # 公开 API 头文件
├── src/
│ ├── dll_main.cpp # DLL 入口 (DllMain)
│ ├── auto_update.cpp # 核心逻辑 (getUpdateInfo / update)
│ ├── latency_checker.h/cpp # 镜像延迟探测
│ └── downloader.h/cpp # 文件下载 & 进程启动
└── updateLists-template.json # 远端更新清单模板
[
{
"version": "2.0.0",
"url": [
"https://mirror1.cdn.com/setup.exe",
"https://mirror2.cdn.com/setup.exe"
],
"priority": "warn",
"changelog": "修复若干 Bug,优化性能"
}
]priority:silent静默 |warn提示可关闭 |force强制(拒绝即退出)url: 多个镜像地址,DLL 自动选择延迟最低的一个changelog: 更新日志文本