I have to call a function in the form f(void* params)
I would like to pass two vector<double> to this function.

I suppose I should make a struct

struct MyParam_t {
vector<double> myvector1;
vector<double> myvector2;
};

and then somehow fill it and pass it to the function. Someone recommended that I use this:

struct MyParam_t {
  vector<double> *myvector1;
  vector<double> *myvector2;
};

but i'm not really sure the difference. Can someone explain how I would fill this struct - My guess was

vector<double> a;
a.push_back(0);
MyParam_t MyParam;
MyParam.myvector1 = a;
f(MyParam)

but it doesn't work.

Also, then when I am in the function and have a variable of type void* called params, how do i get back my variable of type MyParam_t?

Thanks!

Dave

struct MyParam_t {
  vector<double> *myvector1;
  vector<double> *myvector2;
};

Don't do that ^^^^ -- make the struct like you originally thought, see below.

struct MyParam {
  vector<double> myvector1;
  vector<double> myvector2;
};

void fn(void *ptr)
{
    MyParam*p = static_cast<MyParam*>(ptr);
    for(size_t i = 0; i < p->myvector1.size(); i++)
        cout << p->myvector1[i] << "\n";
}


int main(int argc, char* argv[])
{
    vector<double> d;
    d.push_back(1.0);
    d.push_back(2.345);
    MyParam p;
    p.myvector1 = d;
    fn(&d);
	return 0;
}

that is exactly what it needs to do - but now I need to understand!

fn(&d); //pass the address of the beginning of the vector d to the function f

void fn(void *ptr) //accept an address of an unknown type

MyParam*p = static_cast<MyParam*>(ptr); //take the unknown type and force it to be a MyParam called p

My only question is why create a
MyParam*p
instead of a MyParam p ?

(Then you are using the -> operator since it is a MyParam*, but could you have cast to a MyParam and used . instead?)

Thanks!

My only question is why create a
MyParam*p
instead of a MyParam p ?

Because void* is a pointer and you can not case a pointer to a non-pointer. Pointers can only be case to other pointers.

but could you have cast to a MyParam and used . instead?)

Yes, but its more complicated (and looks ugly too) than just using the ->. And you have to do that every time you want to use it. cout << (*p).myvector1[i] << "\n";

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.