玛卡巴卡␃ 2024-09-03 10:39 采纳率: 50%
浏览 1

在LoadLibrary中DLL调用失败,现象为hinst==NULL

#include <iostream>
#include <Ice/Ice.h>
#include <fstream>
#include <sstream>
#include <map>
#include <ctime>
#include <iostream>
#include <windows.h>
#include <cstringt.h>
#include "QString"
#include "Laser.h"
#include "Chat.h"
#include "stdafx.h"
#include "LkIF.h"

#pragma comment(lib, "Advapi32.lib")
#define SAFE_DELETE_ARRAY(p)    {    if(p) { delete [] (p);                    (p)=NULL; }    }

typedef ILaser* (*PGetLaserInstance)(E_LaserType, E_MeasureType, const U_LaserInParam &);
using namespace std;

class ChatRoomI : public Chat::Room {
public:
    virtual bool login(const string& user, const Chat::MessageReceiverPrx& receiver, const Ice::Current&);
    virtual void logout(const string& user, const Ice::Current&);
    virtual void sendMessage(const string& user, const string& message, const Ice::Current&);
    virtual void userLoggedIn(const string& user, const Ice::Current&);
    void loadDocumentData(const string& filename);

private:
    bool notify(const Chat::MessageReceiverPrx& receiver, const string& sender, const string& message);
    void logMessage(const string& user, const string& message, const string& action);

    map<string, Chat::MessageReceiverPrx> users_;
    map<string, string> documentData_;
};

void ChatRoomI::loadDocumentData(const string& filename) {
    ifstream file(filename);
    string line;
    while (getline(file, line)) {
        stringstream ss(line);
        string id, num;
        if (getline(ss, id, ',') && getline(ss, num)) {
            documentData_[id] = num;
        }
    }
    file.close();
}

bool ChatRoomI::login(const string& user, const Chat::MessageReceiverPrx& receiver, const Ice::Current&) {
    if (users_.find(user) != users_.end()) {
        return false;
    }
    users_[user] = receiver;
    logMessage(user, "logged in", "INFO");
    cout << "User " << user << " has logged in successfully." << endl;
    userLoggedIn(user, Ice::Current());
    return true;
}

void ChatRoomI::logout(const string& user, const Ice::Current&) {
    users_.erase(user);
    logMessage(user, "logged out", "INFO");
}

void ChatRoomI::sendMessage(const string& user, const string& message, const Ice::Current&) {
    logMessage(user, message, "sent a message");
    cout << "Message from " << user << ": " << message << endl;
    size_t pos = message.find(":");
    if (pos != string::npos) {
        string command = message.substr(0, pos);
        string query = message.substr(pos + 1);
        if (command == "get") {
            auto it = documentData_.find(query);
            if (it != documentData_.end()) {
                notify(users_[user], "System", "Data: " + it->second);
                logMessage(user, "received data: " + it->second, "INFO");
            }
            else {
                notify(users_[user], "System", "Data not found.");
                logMessage(user, "requested data but not found", "INFO");
            }
            return;
        }
    }
    // 直接发送消息给指定用户
    if (users_.find(user) != users_.end()) {
        notify(users_[user], user, message);
    }
}

bool ChatRoomI::notify(const Chat::MessageReceiverPrx& receiver, const string& sender, const string& message) {
    bool ret = true;
    try {
        receiver->onMessage(sender, message);
    }
    catch (const std::exception& ex) {
        ret = false;
        logMessage(sender, message, "failed to send message");
    }
    return ret;
}

void ChatRoomI::logMessage(const string& user, const string& message, const string& action) {
    time_t now = time(0);
    tm localTime;
    localtime_s(&localTime, &now);  // 使用 localtime_s
    char datetime[64];
    strftime(datetime, sizeof(datetime), "%Y-%m-%d %H:%M:%S", &localTime);
    ofstream logFile;
    logFile.open("chatroom_log.txt", ios::app);
    if (logFile.is_open()) {
        logFile << "[" << datetime << "] " << user << " " << action << " : " << message << endl;
        logFile.close();
    }
    else {
        cerr << "Unable to open log file." << endl;
    }
}

void ChatRoomI::userLoggedIn(const string& user, const Ice::Current&) {
    logMessage("System", user + " has logged in", "INFO");
}

class Server : public Ice::Application {
public:
    virtual int run(int argc, char* argv[]) {
        Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapterWithEndpoints("Chat.RoomAdapter", "default -p 10000");
        ChatRoomI* room = new ChatRoomI;
        room->loadDocumentData("data.txt");
        adapter->add(room, Ice::stringToIdentity("Chat.Room"));
        adapter->activate();
        communicator()->waitForShutdown();
        return 0;
    }
};

int main(int argc, char* argv[]) {
    // 加载DLL文件
    HINSTANCE hinst = NULL;
    hinst = LoadLibrary("Laser.dll");
    if (hinst == NULL) {
        DWORD error = GetLastError();
        // 根据 error 值进行错误处理
        std::cerr << "Failed to load DLL, error code: " << error << std::endl;
        return 1;
    }

    // 获取函数指针
    PGetLaserInstance GetLaserInstance = (PGetLaserInstance)GetProcAddress(hinst, "GetLaserInstance");
    if (GetLaserInstance == NULL) {
        std::cerr << "Failed to get GetLaserInstance function address." << std::endl;
        FreeLibrary(hinst);
        return 1;
    }

    ILaser *m_pLaser;
    E_LaserType laserType;
    U_LaserInParam laserIn;
    memset(&laserIn, 0, sizeof(U_LaserInParam));
    laserType = LKIF;
    E_LKIF_OutNo m_eLaserOutNo;
    m_eLaserOutNo = E_LKIF_OutNo::Out1;
    laserIn.lkif.pOutNo = &m_eLaserOutNo;
    const E_MeasureType measureType = Once;
    m_pLaser = GetLaserInstance(laserType, measureType, laserIn);
    if (nullptr == m_pLaser)
    {
        std::cout << "Inew laser err!" << std::endl;
        FreeLibrary(hinst);
        return 1;
    }


    if (!m_pLaser->Init())
    {
        std::cout << "Init failed" << std::endl;
        FreeLibrary(hinst);
        return 1;
    }

    float m_fCurHeight;
    float m_fAverHeight = 0.0f;
    for (int i = 0; i < 3; i++)
    {
        m_fCurHeight = 0.0f;
        if (!m_pLaser->Measure(m_fCurHeight))
        {
            std::cout << "Measure failed" << std::endl;
            FreeLibrary(hinst);
            return 1;
        }
        else
        {
            std::cout << "Test time: " << i << std::endl;
            std::cout << "Laser measure success,height is: " << m_fCurHeight << "um" << std::endl;
        }
        m_fAverHeight += m_fCurHeight;
    }

    m_fAverHeight = m_fAverHeight / 3;
    std::cout << "Average height is: " << m_fAverHeight << "um" << std::endl;

    m_fAverHeight = 30 - m_fAverHeight / 1000;
    std::cout << "the real distance is: " << m_fAverHeight << "mm" << std::endl;

    // 释放DLL
    FreeLibrary(hinst);
    Server app;
    return app.main(argc, argv);
}
获取的dll一直都是NULL,路径什么的没有问题,其他的dll也不缺

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/a11fa8d1683c4480af8a8dc588567d53.png "#left")

  • 写回答

1条回答 默认 最新

  • 小ᶻZ࿆ 2024-09-03 18:28
    关注

    该回答引用自GPT-4o,由博主小ᶻZ࿆编写:

    根据你提供的代码和描述,问题出现在LoadLibrary函数调用时,无法正确加载Laser.dll,导致hinst返回NULL。这种情况通常表明DLL文件无法被找到或加载。

    问题的原因可能有以下几种:

    1. DLL文件路径问题:虽然你提到路径没有问题,但依然建议再次确认DLL的路径是否绝对正确,尤其是在不同的运行环境下(例如调试模式与发布模式)。

    2. 依赖DLL丢失Laser.dll可能依赖其他的DLL文件,而这些依赖的DLL文件缺失,导致Laser.dll无法被加载。

    3. 文件权限问题:当前用户或运行环境可能没有足够的权限访问或加载DLL文件。

    4. 系统环境变量问题Laser.dll所在目录可能未包含在系统的PATH环境变量中,导致系统找不到该DLL。

    5. DLL文件损坏Laser.dll文件本身可能已损坏,导致无法正确加载。

    可能的解决方案:

    1. 检查DLL文件路径

      • 在代码中打印出DLL的路径,确认路径是否正确无误:
        std::cout << "DLL Path: " << "Laser.dll" << std::endl;
        
      • 如果使用相对路径,尝试切换到绝对路径。
    2. **使用Dependency Walker**:

      • 下载并运行Dependency Walker工具,检查Laser.dll是否依赖于其他DLL,并确认所有依赖的DLL都存在且完整。
    3. 检查文件权限

      • 确保运行环境对Laser.dll文件有足够的读取权限。可以尝试右键点击DLL文件,查看属性,确认权限是否正确。
    4. 将DLL所在目录添加到系统PATH

      • Laser.dll的路径添加到系统的PATH环境变量中,并重新启动程序。
    5. 尝试重下载或重新编译DLL文件

      • 如果可能,尝试重新获取Laser.dll文件,确保文件未损坏。
    6. 使用SetDllDirectory函数

      • 在加载DLL之前,使用SetDllDirectory函数明确指定DLL所在的目录:
        SetDllDirectory("C:\\Path\\To\\DLL\\Directory");
        HINSTANCE hinst = LoadLibrary("Laser.dll");
        

    通过这些方法,你应该能够找到并解决LoadLibrary函数加载DLL失败的问题。

    如有帮助,可以采纳一下嘛,谢谢~

    评论

报告相同问题?

问题事件

  • 创建了问题 9月3日

悬赏问题

  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色
  • ¥15 求一份华为esight平台V300R009C00SPC200这个型号的api接口文档
  • ¥15 字符串比较代码的漏洞
  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?