简体   繁体   中英

How to return a char * from a Windows Thread function

Hello this is somewhat of a multilayered question but basically I want my thread function to return a char *, and then I want to be able to access that result once the thread has terminated.

Currently I am type casting the char * to a DWORD at the end of my thread function like: (openPorts is my char *)

DWORD openPortsD = (DWORD)openPorts;

and then immediately returning openPortsD. But this does not seem to be working.

My thread creation logic looks like:

for (int j = 0; j < MAX_THREADS; j++)
{
  pDataArray[j] = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MYDATA));

  if(pDataArray[j] == NULL)
  {
      ExitProcess(2);
  }
  pDataArray[j]->ip = ip;

  hThreadArray[j] = CreateThread(NULL, 0, connectPortW,  pDataArray[j], 0, &dwThreadIdArray[j]);

  if (hThreadArray[j] == NULL) 
  {
     ExitProcess(3);
  }
}

After I loop through my threads I then wait for my threads and then free/close them like:

WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);

for(int j = 0; j < MAX_THREADS; j++)
{
  CloseHandle(hThreadArray[j]);
  if(pDataArray[j] != NULL)
  {
    HeapFree(GetProcessHeap(), 0, pDataArray[j]);
    pDataArray[j] = NULL;    // Ensure address is not reused.
  }
}

Now the second part would be how do I get the returned value. I understand I am supposed to use GetExitCodeThread() but I am unsure how to use it for multiple threads running. Moreover, since the return value will be a DWORD how do I get back my original string?

You are already passing a structure to the thread, the best solution is to add a field to it for the thread to fill in.

typedef struct {
  const char *ip;
  const char *openports;
} MYDATA, *PMYDATA;

DWORD CALLBACK connectPortW(LPVOID ThreadParam)
{
  PMYDATA data = (PMYDATA) ThreadParam;
  data->openports = allocatestringandfillitwithlistofports(data->ip);
  return 0;
}

...

WaitForMultipleObjects(MAX_THREADS, hThreadArray, TRUE, INFINITE);
for(int j = 0; j < MAX_THREADS; j++)
{
  CloseHandle(hThreadArray[j]);
  if(pDataArray[j] != NULL)
  {
    parseandfreeports(pDataArray[j]);
    HeapFree(GetProcessHeap(), 0, pDataArray[j]);
    pDataArray[j] = NULL;    // Ensure address is not reused.
  }
}

If this is a list of IP ports then it is better to store the ports in a array of SHORTs rather than a string.

As noted in the comments, you could allocate some memory and return it as the thread exit code in a 32-bit application but since a 64-it pointer does not fit in 4 bytes it would be impossible to port it to 64-bit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM