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

时间:2019-02-25 14:17:49

标签: c++ multithreading

我正在使用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以便能够从线程内部访问结构数组?

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

它是c风格的方法。但是我宁愿选择已经得到解答的C ++样式。