【发布时间】:2019-05-19 18:33:34
【问题描述】:
我正在使用 c++ 编写一个程序,我试图在 Windows 中使用 WriteProcessMemory() 函数。为此,我需要一个获取目标进程 ID 的函数。我可以使用以下功能做到这一点:
#pragma once
#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
//get process id from executable name using tlhelp32snapshot
DWORD GetProcID(wchar_t *exeName){
PROCESSENTRY32 procEntry = {0};
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (!hSnapshot) {
return 0;
}
procEntry.dwSize = sizeof(procEntry);
if (!Process32First(hSnapshot, &procEntry)) {
return 0;
}
do {
if (!wcscmp(procEntry.szExeFile, exeName)) {
CloseHandle(hSnapshot);
return procEntry.th32ProcessID;
}
} while (Process32Next(hSnapshot, &procEntry));
CloseHandle(hSnapshot);
return 0;
}
//main function
int main() {
using namespace std;
cout << "some output" << endl;
return 0;
}
如果我将字符集设置为 unicode,我可以使用 Visual Studio 进行编译,但是当我尝试使用 g++ 时出现转换错误:
g++ -std=c++17 write.cpp
write.cpp:1:9: warning: #pragma once in main file
#pragma once
^
write.cpp: In function 'DWORD GetProcID(wchar_t*)':
write.cpp:21:43: error: cannot convert 'CHAR* {aka char*}' to 'const wchar_t*' for argument '1' to 'int wcscmp(const wchar_t*, const wchar_t*)'
if (!wcscmp(procEntry.szExeFile, exeName)) {
^
write.cpp: In function 'MODULEENTRY32 GetModule(DWORD, wchar_t*)':
write.cpp:40:46: error: cannot convert 'char*' to 'const wchar_t*' for argument '1' to 'int wcscmp(const wchar_t*, const wchar_t*)'
if (!wcscmp(modEntry.szModule, moduleName)) {
^
我能够使用 cl 使用参数进行编译:
cl /EHsc /D UNICODE write.cpp
这里/D UNICODE 与进入visual studio > rmb on project > properties 并将Character Set 设置为Use Unicode Character Set 相同。
是否可以像在 cl 中一样在 g++ 中强制使用 unicode?p>
【问题讨论】:
-
是的,g++ 有
-DUNICODE参数。或者你可以直接在你的代码中#define UNICODE。 (我会删除#pragma once,它不是标题) -
嘿,非常感谢。我之前使用了
#define UNICODE,但它没有用,所以我把它拿出来,但我尝试了-DUNICODE,它确实有效。非常感谢。 -
你应该使用
W的东西:PROCESSENTRY32W等等。如果在第一个 return 语句返回,这个函数也会泄漏资源。 -
使用
-municode开关(假设您使用的是mingw-w64),以及定义UNICODE它还链接正确版本的main等等
标签: c++ windows unicode g++ cl