所以由于某种原因,我的GetProcessID函数在一个项目中运行(编译源代码时没有错误),但是最近我刚开始一个新项目,现在却遇到了错误
'int strcmp(const char *,const char *)': cannot convert argument 1 from 'WCHAR [260]' to 'const char *'
但是为什么我什至无法将其从WCHAR转换为const char *错误?如果将鼠标悬停在p32.szExeFile上,则szExeFile的类型为CHAR [260],而不是WCHAR。另外,我进入属性页并选择“使用多字节字符集”。即使我将std :: string processName参数更改为
const char *processName
或
char *processName
wchar_t *processName
我仍然遇到相同的错误。
所以我的问题是:为什么我的GetProcessID函数可以在另一个项目中运行而没有任何编译错误,但是当我尝试在全新项目中使用相同的函数时却出现错误?
DWORD GetProcessID(std::string processName)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE)
{
std::cout << "CreateToolhelp32Snapshot() (of processes)" << std::endl;
std::cin.get();
return 0;
}
if (!Process32First(hSnapshot, &pe32))
{
CloseHandle(hSnapshot);
std::cout << "The first entry of the process list wasn't copied to the buffer." << std::endl;
std::cin.get();
return 0;
}
while (Process32Next(hSnapshot, &pe32))
{
if (strcmp(pe32.szExeFile, processName.c_str()) == 0)
{
CloseHandle(hSnapshot);
return pe32.th32ProcessID;
}
}
CloseHandle(hSnapshot);
return 0;
}
int main()
{
DWORD dwProcessID = NULL;
while (dwProcessID == NULL)
{
dwProcessID = GetProcessID("proc.exe");
}
std::cout << "Found PID " << dwProcessID << std::endl;
std::cin.get();
return 0;
}
答案 0 :(得分:4)
失败的项目被编译为Unicode。当您这样做时,PROCESSENTRY32
中的字符串被定义为WCHAR []
而不是char []
。
一种解决方案是显式编码PROCESSENTRY32A
(和Process32FirstA
/ Process32NextA
),尽管Unicode字符串能够更好地表示非ASCII字符。