将变量传递给WIN32 API LPCWSTR?

时间:2016-12-31 08:22:42

标签: c++ winapi

最近我为我的软件制作了更新客户端。它使用WinHTTP连接到我公司的服务器,我想在WinHttpOpen的WINDOWS API的用户代理部分添加一个特殊的字符串。我需要将一个变量传递给WinHttpOpen的pwszUserAgent,它是LPCWSTR。

这是我的代码的一部分

//convert string to wstring
wstring s2ws(const string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    wstring r(buf);
    delete[] buf;
    return r;
}


//This defined string indicates a string variable I got previously
string MyVariable_grabbed_previously = "version:15.3, Date:2016/12/10"
//a flag indicate if version string variable exists
bool Version_variable = TRUE;

//define LPCWSTR for winAPI user-agent section
LPCWSTR UserAgent;

if (Version_variable) {
//version variable exist
        string UA = "my custom UA & version" + MyVariable_grabbed_previously;
        wstring UAWS = s2ws(UA);
        UserAgent = UAWS.c_str();



    }
    else {
//Version variable not exist
        UserAgent = L"my custom UA";

    }


hSession = WinHttpOpen(UserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);

然而,似乎我的程序一直使用空字符串作为User-agent,我想知道为什么我的值无法正确传递? 我是Windows API的新手。

1 个答案:

答案 0 :(得分:3)

问题是您向WinHttpOpen()传递了无效指针。您正在创建一个临时 std::wstring对象,抓取指向其数据的指针,然后在 <{1}}被销毁之后传递该指针

将您的std::wstring变量改为UserAgent,然后在准备好传递时使用std::wstring,例如:

c_str()

wstring s2ws(const string& s)
{
    wstring r;
    int slength = s.length();
    if (slength > 0)
    {
        int len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
        r.resize(len);
        MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, &r[0], len);        
    }
    return r;
}