c++nlopt

How to properly cast std::vector< std::vector<double> > to void* and reinterpret it back?


I am not an expert in c++ and I have a problem with casting a std::vector< std::vector<double> > my_data to a void *f_data and reinterpreting this cast.

Basically I need to convert my_data:

std::vector<double> point1(2);
point1[0] = 0.06; point1[1] = 2.07;
std::vector<double> point2(2);
point2[0] = 1.01; point2[1] = 0.02;
std::vector< std::vector<double> > my_data;
my_data.push_back(point1);
my_data.push_back(point2);

so that it fits the opt.set_min_objective(vfunc vf, void *f_data) function coming from the NLopt package in c++.

Based on this post, I am trying the following but it does not work:

auto *test = static_cast<void*>(my_data.data());
std::vector< std::vector<double> > *this_data = reinterpret_cast<std::vector< std::vector<double> >*>(test);

as I get the following error while debugging:

this_data=Cannot access memory at address 0x3faeb851eb851eb8

I have also tried this but it does not work either:

auto test = static_cast<void*>(my_data.data());
std::vector< std::vector<double> > *this_data = reinterpret_cast<std::vector< std::vector<double> >*>(test);

Any help would be great. Thanks!


Solution

  • The setup code would be:

    opt.set_min_objective(vf, &my_data);
    

    and then inside the vf function to retrieve a pointer to the original:

    static_cast< std::vector<std::vector<double>>* >(f_data)
    

    which you might like to use to initialize a reference:

    auto& my_data = *static_cast< std::vector<std::vector<double>>* >(f_data);
    

    Readability could be improved by a using declaration for the data type.