错误:无法在 VS 代码中将“CHAR*”{aka 'char*'} 转换为“const wchar_t*”

Error: cannot convert 'CHAR*' {aka 'char*'} to 'const wchar_t*' in VS code

提问人:moondog85 提问时间:11/13/2023 最后编辑:Adrian Molemoondog85 更新时间:11/13/2023 访问量:36

问:

注意:初始化 'int wcscmp(const wchar_t*, const 的参数 1 wchar_t*)' 134 |int __cdecl wcscmp(const wchar_t *_Str1,const wchar_t *_Str2);

我无法弄清楚为什么它在尝试构建时会抛出此错误。

DWORD GetPidByName(const wchar_t * pName) {
    PROCESSENTRY32 pEntry;
    HANDLE snapshot;

    pEntry.dwSize = sizeof(PROCESSENTRY32);

    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (Process32First(snapshot, &pEntry) == TRUE) {
        while (Process32First(snapshot, &pEntry) == TRUE) {
            if (wcscmp(pEntry.szExeFile, pName) == 0) {
                return pEntry.th32ProcessID;
            }    
        }
    }
}

该错误与转换有关。wchar_t *

可视化 C++

评论

0赞 Nick is tired 11/13/2023
PROCESSENTRY32.szExeFile 似乎是 ,而不是 .CHAR[]const wchar_t*

答:

0赞 Adrian Mole 11/13/2023 #1

您正在尝试使用带有 name 参数的函数和结构的 ANSI 版本(即那些将 C 字符串作为基于 - 的版本)。这是行不通的。charProcess32FirstPROCESSENTRY32wchar_t

要么将你的参数更改为一个类型,或者,如果这是不可取的和/或不可能的,那么使用上述函数和结构的“Unicode”(基于)版本(其名称中添加了一个尾部“W”),如下所示:pNameconst char*wchar_t

#include <Windows.h>
#include <tlhelp32.h>

DWORD GetPidByName(const wchar_t* pName)
{
    PROCESSENTRY32W pEntry; // Note added trailing "W" - .szExeFile is now wchar_t[]
    HANDLE snapshot;

    pEntry.dwSize = sizeof(PROCESSENTRY32W);

    snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    // Use the function with the added "W" at the end of the name...
    if (Process32FirstW(snapshot, &pEntry) == TRUE) {
        while (Process32FirstW(snapshot, &pEntry) == TRUE) {
            if (wcscmp(pEntry.szExeFile, pName) == 0) {
                return pEntry.th32ProcessID;
            }
        }
    }
    return 0; // Need to return SOMETHING, here, to signal a "not found" result!
}

注意:与许多(大多数)WinAPI 结构和函数不同,这些结构和函数被定义为根据生成设置(无论是否定义了 _UNICODE 令牌)解析为 ANSI 或 Unicode 版本的宏,对于这些工具帮助库函数/结构,如果需要或需要,则需要显式调用/使用wchar_t版本。

评论

0赞 moondog85 11/13/2023
伟大!问题解决了,我能够建造。干杯!