Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a void pointer to array of classes

I am trying to convert a void pointer to an array of classes in a callback function that only supports a void pointer as a means of passing paramaters to the callback.

class person
{
    std::string name, age;
};
void callback (void *val)
{
    for (int i = 0; i < 9; i++)
    {
        std::cout << (person [])val[i].name;
    }
}
int main()
{
    person p[10];
    callback((void*)p);
}

My goal is to be able to pass an array of the class person to the callback which then prints out the data such as their name and age. However, the compile does not like what I am doing and complains that error: request for member 'name' in 'val', which is of non-class type 'void*' How can I go about doing this?

like image 994
user99545 Avatar asked Feb 24 '26 18:02

user99545


1 Answers

If you want to be able to recover the size, you need to use a container which keeps track of the size at runtime. I'd suggest using a std::vector instead of a raw array.

std::vector<person> p(10);
static_cast<std::vector<Person>*>(val);
like image 106
Antimony Avatar answered Feb 27 '26 07:02

Antimony