'How can i pass a string as parameter for a thread in Windows?

I'm studying threads in c++. I'm using the CreateThread() function from windows.h library:

#include <windows.h>
#include <iostream>
#include <unistd.h>


DWORD WINAPI ThreadFunc(void* data, std::string message) {
    std::cout<<message;
  return 0;
}

int main() {
  std::string saluti="hi";
  HANDLE thread = CreateThread(NULL, 0, ThreadFunc, &saluti, 0, NULL);
  sleep(5);
  
}

The error:

 error: invalid conversion from 'DWORD (__attribute__((__stdcall__)) *)(void*, std::__cxx11::string) {aka long unsigned int (__attribute__((__stdcall__)) *)(void*, std::__cxx11::basic_string<char>)}' to 'LPTHREAD_START_ROUTINE {aka long unsigned int (__attribute__((__stdcall__)) *)(void*)}' [-fpermissive]
   HANDLE thread = CreateThread(NULL, 0, ThreadFunc, &saluti, 0, NULL);
                                                                     ^

how can i pass a std::string to a thread function?



Solution 1:[1]

The thread start routine needs to have the signature:

DWORD __stdcall ThreadFunc(LPVOID lpThreadParameter);

So, you need to cast the void* into the pointer type which you sent into the function:

DWORD WINAPI ThreadFunc(LPVOID lpThreadParameter) {
    std::string& message = *static_cast<std::string*>(lpThreadParameter);
    std::cout<<message;
    return 0;
}

Just note that the string must not be destroyed while the thread is using it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ted Lyngmo