简体   繁体   中英

Passing a variable to WIN32 API LPCWSTR?

Recently I've made an update client for my software. It uses WinHTTP to connect to my company's server, I wanted to add a special string in the user-agent section of WINDOWS API in WinHttpOpen. I need to pass a variable to pwszUserAgent of WinHttpOpen which is LPCWSTR.

Here's part of my code

//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);

However it seems my program kept using empty string as User-agent, I wonder why my value can not be passed correctly? I'm new to Windows API.

The problem is that you are passing an invalid pointer to WinHttpOpen() . You are creating a temporary std::wstring object, grabbing a pointer to its data, and then passing that pointer after the std::wstring is destroyed.

Change your UserAgent variable to std::wstring instead, and then use c_str() when you are ready to pass it, eg:

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;
}

string MyVariable_grabbed_previously = "version:15.3, Date:2016/12/10"; 
bool Version_variable = true;    
wstring UserAgent;

...

if (Version_variable) {
    UserAgent = s2ws("my custom UA & " + MyVariable_grabbed_previously);
}
else {
    UserAgent = L"my custom UA";
}

/* Alternatively:
UserAgent = L"my custom UA";
if (Version_variable) {
    UserAgent += (L" & " + s2ws(MyVariable_grabbed_previously));
}
*/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM