How to send a string to _beginthreadex for the thread to read it?

163 Views Asked by At

I want to use _beginthreadex and pass a character string, the name of a domain. What is the proper way/best practice to pass it?

  1. By variable itself (sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, sDomain, 0, &threadID);
  1. Or by the address of the variable (&sDomain)?
    WCHAR sDomain[256] = {0};
    //...copy domain into sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, &sDomain, 0, &threadID);
  1. Or do I make a struct and pass the struct element (&sDomain[0])?
    struct strDomain {TCHAR sDomain[256];};
    strDomain *sDomain = new strDomain[1]();
    //...copy domain into strDomain[0].sDomain
    UINT threadID = 0;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, &sDomain[0], 0, &threadID);
1

There are 1 best solutions below

0
superman On BEST ANSWER

The following is the simplest code to implement, of course you can customize some type to pass, because the thread function argument type is void, you can do any conversion

#include <iostream>
using namespace std;

UINT Thread_SaveDomainName(LPVOID params)
{
    char* szDomain = (char*)params;
    cout<<szDomain<<endl;
    
    return 0;
}

int main()
{
    char* szDomain = "8080";
    UINT threadID = -1;
    HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &Thread_SaveDomainName, (void*)szDomain, 0, &threadID);
    
    return 0;
}