Question

Here is the problem. I use minpack for non-linear optimization. The cost function has the following signature:

void cost_function(const int* n, const int* m,const double *p, double *x, int* iflag)

n - size of initial point m - size of function vector p - initial point x - function vector

I have for loop, where i iterate through the array of objects. Each object contain input information for optimization function.

for(int counter = 0; i < num_of_objects; ++counter)
{
    //get information from object
    //call optimization function
    lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}

but in cost function i need particular values connected with current object. If cost function would be a class member, then the pointer will have wrong type, and it will be impossible to pass this pointer to lmdif1_.

So now i have a temporary solution, using global object.

for(int counter = 0; i < num_of_objects; ++counter)
{
    //get information from object
    //call optimization function
    global_obj = object;
    lmdif1_(cost_function, m, n, initial_point, X, precision, info, iwa, wa, lwa);
}

Then cost_function uses this global object to recieve needed information. But it's not good. What is the right solution for this problem? Thanks.

Was it helpful?

Solution

If those m, n, fvec arrays can be class members, you could maybe use the offsetof macro to recover the address of the class. (For how to do that, read this explanation of the non-standard container_of macro)

If they're dynamically allocated, it's harder, but you could allocate extra space in the buffer, and put a pointer to your class in front of the actual array data.

OTHER TIPS

You will have to use a global object.

There is the possibility of using thunks but these are complicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top