簡體   English   中英

如何將wchar [260]和wchar_t轉換為const char *

[英]how to convert wchar[260] and wchar_t to const char *

此代碼應檢查指定的進程是否正在運行,但是在調用stricmp時失敗,其中兩個參數都需要const char *。 如何將變量processName和結構entry.szExeFile的成員(即wchar [260])轉換為const char *?

 bool IsProcessRunning(wchar_t processName)

{ bool exists = false;


    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry))
        while (Process32Next(snapshot, &entry)){
            if (stricmp(entry.szExeFile, processName) == 0){
                exists = true;

                CloseHandle(snapshot);
                return exists;
            }
        }
int _tmain(int argc, _TCHAR* argv[])
{

    if (IsProcessRunning(argv[0])) { cout << "Process " << argv[0] << "is running"; }
    return 0;
}

而是在wchar和char之間轉換,為什么不使用wcsicmp函數比較兩個字符串。 確保兩個參數(entry.szExeFile,processName)均為LPCWSTR。 更好的是為什么不使用安全功能以安全方式進行比較。

如您所見,您已經在使用WIN API,因此可以嘗試MultiByteToWideChar


char* Convert (const std::wstring &data)
{
    if (data.empty()) 
        return "";

    int iLn = WideCharToMultiByte (CP_UTF8, 0, const_cast<LPWSTR> (data.c_str()), static_cast<int>(data.length()), NULL, 0, NULL, NULL);
    if( iLn == 0 )
    {
        return "";
    }

    std::string result (iLn, 0);
    WideCharToMultiByte (CP_UTF8, 0, data.c_str(), static_cast<int>(data.length()), const_cast<LPSTR> (result.c_str ()), iLn, NULL, NULL);

    return result.c_str();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM