1

我在 Qt4 上编写了一个简单的应用程序来修改网络适配器参数,为此我有一个名为 的插槽setInterfaceParams,实现如下:

DWORD WinNetInterface::setInterfaceParams(QString index, QString ip, QString netmask, QString gateway)
{
    DWORD res = NULL;
    HINSTANCE lib = (HINSTANCE) LoadLibrary((WCHAR *)"iphlpapi.dll");
    _SetAdapterIpAddress SetAdapterIpAddress = (_SetAdapterIpAddress) GetProcAddress(lib, "SetAdapterIpAddress");

    PWSTR pszGUID = NULL;
    //char  *szGUID = (char *)index.toStdString().c_str();
    QByteArray a = index.toLocal8Bit();
    char  *szGUID = a.data();
    WideCharToMultiByte(CP_ACP, 0, pszGUID, -1, szGUID, sizeof(szGUID), NULL, NULL);


// Method 01
    res = SetAdapterIpAddress(szGUID,
                        0,
                        inet_addr(ip.toStdString().c_str()),
                        inet_addr(netmask.toStdString().c_str()),
                        inet_addr(gateway.toStdString().c_str()));
// End of method 01

// Method 02
    /*res = SetAdapterIpAddress("{422C5689-A17B-402D-A6A2-22CE13E857B5}",
                                0,
                                inet_addr("192.168.1.10"),
                                inet_addr("255.255.255.0"),
                                inet_addr("192.168.1.1"));*/
// End of method 02
    return res;
}

当我单击连接到 slot 的按钮时,出现setInterfaceParams分段错误。如果我评论method01,什么都不会发生,当我使用method02时会发生一些事情。我在一个简单的 c++ 应用程序上尝试了这个功能,它工作正常,在 Windows XP SP3 上测试。

#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <iostream>


typedef DWORD (WINAPI *_SetAdapterIpAddress )(char *szAdapterGUID, 
                                              DWORD dwDHCP, 
                                              DWORD dwIP, 
                                              DWORD dwMask, 
                                              DWORD dwGateway); 


int main()
{
    HINSTANCE lib = (HINSTANCE) LoadLibrary("iphlpapi.dll"); 
    _SetAdapterIpAddress SetAdapterIpAddress = (_SetAdapterIpAddress) GetProcAddress(lib, "SetAdapterIpAddress");

    PWSTR pszGUID = NULL;
    char  szGUID[] = "{422C5689-A17B-402D-A6A2-22CE13E857B5}";
    DWORD dwSize = 0;
    WideCharToMultiByte(CP_ACP, 0, pszGUID, -1, szGUID, sizeof(szGUID), NULL, NULL);

    DWORD res = SetAdapterIpAddress(szGUID, 
                        0, 
                        inet_addr("192.168.1.10"),
                        inet_addr("255.255.255.0"),
                        inet_addr("192.168.1.1"));

    std::cout << res;                   

    return 0;
}
4

1 回答 1

1
LoadLibrary((WCHAR *)"iphlpapi.dll");

那行不通,文字字符串是 8 位的,没有真正转换的情况下强制转换不会使其变宽,因此 dll 加载可能失败。

您应该在传递给 WinAPI 函数的大多数文字字符串周围使用TEXTor_T宏,以根据编译选项使它们成为常规或宽:

LoadLibrary(_T("iphlpapi.dll"));

which will translate to either LoadLibrary("iphlpapi.dll"); or LoadLibrary(L"iphlpapi.dll");.

Also you should always check the value returned by the LoadLibrary and GetProcAddress functions, which return NULL if the call is unsuccessful.

于 2012-07-07T12:24:45.623 回答