Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass structure to function via pointer

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?

like image 335
0x29a Avatar asked Apr 16 '26 02:04

0x29a


1 Answers

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.

like image 146
molbdnilo Avatar answered Apr 18 '26 17:04

molbdnilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!