lastpeony4
lastpeony4

Reputation: 577

How to cast void* to vector<char *>?

There is a function which takes void*

After passing my vector<char*>, how do I cast it back to vector<char*> and print its content using casting in C++?

Example:

void testFunction(void* data){

   //cast data back to vector<char *> and print its content


}


int main()
{
   std::vector<char *> arg(1);
    std::string someString = "testString";
        arg[0] = (char *)someString.c_str();
        testFunction(&arg);
    return 0;
}

Upvotes: 0

Views: 338

Answers (3)

lastpeony4
lastpeony4

Reputation: 577

std::vector<char*>& myVec= *reinterpret_cast<std::vector<char*>*>(data);
std::cout<<myVec[0];

Well actually this worked.

Upvotes: 1

kmodexc
kmodexc

Reputation: 105

Just use reinterpret_cast

vector<char*>* parg = reinterpret_cast<vector<char*>*>(data);
char* mystr = parg->at(0);

Upvotes: 2

Adrian Mole
Adrian Mole

Reputation: 51825

You can use a static_cast to cast a void* pointer to almost any other type of pointer. The following code works for me:

void testFunction(void* data)
{
    std::vector<char*>* vecdata = static_cast<std::vector<char*>*>(data);
    for (auto c : *vecdata) std::cout << c;
    std::cout << std::endl;
}

Upvotes: 3

Related Questions