[Solved] reinterpret cast of std vector of std string [closed]


As PaulMcKenzie suggested in the comments, this should work.

#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();
}

4

solved reinterpret cast of std vector of std string [closed]