3

I'm using Win32 API and the _beginthreadex call to run a thread the following way:

struct StructItem
{
   std::string title;
   int amount;
};

StructItem structItems[33];
unsigned int id;
HANDLE thread = (HANDLE)_beginthreadex(NULL, 0, my_thread, (void*)structItems, 0, &id);

And this is my thread:

unsigned int __stdcall my_thread(void *p)
{
    for (int i = 0; i < 20; i++)
    {           
        // todo: print struct.title
        Sleep(1000);
    }

    return 0;
}

As far as I understood the *p is a pointer to my list of structures, since I passed them to the 4th argument in the _beginthreadex call, but I can't understand how can I cast the *p so that I can access the array of structs from within the thread?

5
  • (StructItem*)p; maybe? Commented Feb 25, 2019 at 14:20
  • @πάνταῥεῖ but it's an array of structs, instead of a single struct Commented Feb 25, 2019 at 14:20
  • @0x29a Do you really need to use the Win32 threads? Since C++11, there's std::thread. Commented Feb 25, 2019 at 14:26
  • @TedLyngmo I had trouble getting the std::thread to run in the background, it kept hanging the main UI and I could not solve it, I will give it another shot, thanks! Commented Feb 25, 2019 at 14:28
  • @0x29a See here: stackoverflow.com/questions/1461432/what-is-array-decaying Commented Feb 25, 2019 at 14:32

2 Answers 2

7

Since the array decays into a StructItem* (the location of the array's first element) when you pass it as an argument, cast it back to StructItem*.

unsigned int __stdcall my_thread(void *p)
{
    auto items = static_cast<StructItem*>(p);
    for (int i = 0; i < 20; i++)
    {           
        std::cout << items[i].title << '\n';
        Sleep(1000);
    }
    return 0;
}

Note that the cast to void* is entirely unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

1

You could cast void pointer to the pointer type of your struct, and then dereferencing that pointer expression to get the element at a particular offset:

*((StructItem*) p); /* first element */
*((StructItem*) p+ 1); /* second element */

Its a c-style method. However I would rather prefer C++ style which is already answered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.