我的编译器不喜欢这个:
std::vector<std::string> data = reinterpret_cast<std::vector<std::string>>(lParam);
我认为双>>
标记存在问题?如何解决这个问题?
更新
它现在编译,但我的程序崩溃了!这是为什么?我认为C ++程序是类型安全的,一旦编译就不会崩溃。
#include <stdio.h>
#include <string>
#include <vector>
#include <windows.h>
BOOL CALLBACK cbEnum(HWND hwnd, LPARAM lParam)
{
std::vector<std::string> data = reinterpret_cast<std::vector<std::string>&>(lParam);
return TRUE;
}
std::vector<std::string> listWindows()
{
std::vector<std::string> result;
EnumWindows(cbEnum, reinterpret_cast<LPARAM>(&result));
return result;
}
int main()
{
listWindows();
}
答案 0 :(得分:0)
正如PaulMcKenzie在评论中所说,这应该有效。
#include <stdio.h>
#include <string>
#include <vector>
#include <windows.h>
static_assert(sizeof(LPARAM) == sizeof(void *), "LPARAM must be large enough to store a pointer");
constexpr size_t MAX_TITLE_LENGTH = 128;
BOOL CALLBACK cbEnum(HWND hwnd, LPARAM lParam)
{
std::vector<std::string> *data = reinterpret_cast<std::vector<std::string> *>(lParam);
char title[MAX_TITLE_LENGTH];
//the title is truncated if it exceeds the limit
GetWindowText(hwnd, title, static_cast<int>(MAX_TITLE_LENGTH));
data->push_back(title);
return TRUE;
}
std::vector<std::string> listWindows()
{
std::vector<std::string> result;
EnumWindows(cbEnum, reinterpret_cast<LPARAM>(&result));
return result;
}
int main()
{
listWindows();
}