通过指针将结构传递给函数

问题描述 投票:3回答:2

我正在使用Win32 API和_beginthreadex调用以下列方式运行线程:

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);

这是我的主题:

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

    return 0;
}

据我所知,* p是指向我的结构列表的指针,因为我将它们传递给_beginthreadex调用中的第4个参数,但我无法理解如何转换* p以便我可以访问数组线程内的结构?

c++ multithreading
2个回答
7
投票

由于当您将其作为参数传递时,数组会衰减为StructItem*(数组的第一个元素的位置),因此将其强制转换为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;
}

请注意,对void*的演员是完全没必要的。


1
投票

您可以将void指针强制转换为结构的指针类型,然后取消引用该指针表达式以获取特定偏移量的元素:

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

它是一种c风格的方法。但是我更喜欢已经回答的C ++风格。

© www.soinside.com 2019 - 2024. All rights reserved.