c++nlopt

nlopt: Passed data structure gives me damaged values


I need to pass structure to the function Constraint::AddFixedOrientationAxis, however when I check the passed data their values are completely wrong. I have tried to use different datatypes but without any luck.

typedef struct{
    size_t idx;
    size_t axis_idx;
    double axis_vector_1;
    double axis_vector_2;
    double axis_vector_3;
}AddFixedOrientationAxisData;


double Constraint::AddFixedOrientationAxis(const std::vector<double> &x, std::vector<double> &grad, void *data)
{
    Eigen::VectorXd fixed_rot(3);

    AddFixedOrientationAxisData *d = reinterpret_cast<AddFixedOrientationAxisData*>(data);
    auto idx = d->idx;
    auto axis_idx = d->axis_idx; // 0->x, 1->y, 2->z
    fixed_rot << d->axis_vector_1, d->axis_vector_2, d->axis_vector_3;


    std::cout << "idx: " << idx << std::endl;
    std::cout << "axis: " << axis_idx << std::endl;
    std::cout << "fixed_rot: " << fixed_rot << std::endl;
}

In the main, I call use it the same way as the tutorial is:

AddFixedOrientationAxisData fixed_orient_constraint_data;
fixed_orient_constraint_data.idx = 0;
fixed_orient_constraint_data.axis_idx = 0;
fixed_orient_constraint_data.axis_vector_1 = FK_q(0,0);
fixed_orient_constraint_data.axis_vector_2 = FK_q(1,0);
fixed_orient_constraint_data.axis_vector_3 = FK_q(2,0);
opt.add_equality_constraint(Constraint::AddFixedOrientationAxis, &fixed_orient_constraint_data);

The terminal output is:

idx: 93901286131024
axis: 93901286131080
fixed_rot: 
4.63934e-310
-0.54938          //interestingly, this is the correct value
0.00838157        //interestingly, this is the correct value

Solution

  • As @{Some programmer dude} told me in the comments, the problem was that the variable was not alive when the function was called.