C++加载dll失败

使用Dependencies查找依赖项也有点过于复杂,写了一个简单的用来判断dll是否可以加载,都放在一个文件夹里来帮助判断

void checkDLL(std::string directory){
    HINSTANCE handle;
    for (const auto& entry : fs::directory_iterator(directory)) {
        if (fs::is_regular_file(entry.path())) {
            handle = LoadLibrary(entry.path().string().c_str());
            if (handle == NULL) {
                std::cout << "File: " << entry.path().string() << std::endl;
            }
        }
    }
}

仅供参考

const char* dllPath = "ur path";
    if (fs::exists(dllPath)) {
        std::cout << "File exists." << std::endl;
    } else {
        std::cout << "File does not exist." << std::endl;
    }
    HINSTANCE handle = LoadLibraryEx(dllPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
    AlgoCreatorPtr* list_ptr{};
    uint32_t list_size{};
    uint32_t* creator_size_ptr{};
    if (handle != NULL) {
       
    } else {

        DWORD error = GetLastError(); // 获取错误代码
        std::cerr << "Failed to load DLL. Error code: " << error << std::endl;
        LPVOID errorMsg;
        FormatMessageA(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
            NULL,
            error,
            0, // 默认语言
            (LPSTR)&errorMsg,
            0,
            NULL);

        if (errorMsg != NULL) {
            std::cerr << "Error message: " << static_cast<LPSTR>(errorMsg) << std::endl;

            // 释放由 FormatMessage 分配的缓冲区
            LocalFree(errorMsg);
        }
    }

补充:
添加了getLastError来进行分析加载失败原因。
记录一下,我之前使用LoadLibrary时失败,且发现该dll其中的几个依赖项也无法加载。
在经历了痛苦的搜索后,发现可以使用LoadLibraryEx,提供更多的选项操作。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值