Introduction

Passing Data to User-Supplied Functions

In some cases it may be advantageous to pass problem-specific data to a user-supplied function through the IMSL C Math Library interface.  This ability can be useful if a user-supplied function requires data that is local to the user's calling function, and the user wants to avoid using global data to allow the user-supplied function to access the data.  Functions in IMSL C Math Library that accept user-supplied functions have an optional argument(s) that will accept an alternative user-supplied function, along with a pointer to the data, that allows user-specified data to be passed to the function.  The example below demonstrates this feature using the IMSL C Math Library function imsl_f_min_uncon and optional argument IMSL_FCN_W_DATA.

Example

#include <imsl.h>

#include <math.h>

#include <stdio.h>

 

static float fcn_w_data(float x, void *data);

 

int main()

{

   float a = -100.0;

   float b = 100.0;

   float fx, x;

   float usr_data[] = {5.0, 10.0};

   x = imsl_f_min_uncon (NULL, a, b,

      IMSL_FCN_W_DATA, fcn_w_data, usr_data,

      0);

   fx = fcn_w_data(x, (void*)usr_data);

 

   printf ("The solution is: %8.4f\n", x);

   printf ("The function evaluated at the solution is: %8.4f\n", fx);

}

 

/*

* User function that accepts additional data in a (void*) pointer.

* This (void*) pointer can be cast to any type and dereferenced to

* get at any sort of data-type or structure that is needed.

* For example, to get at the data in this example

*  *((float*)data)   and usr_data[0] contains the value  5.0

*  *((float*)data+1) and usr_data[1] contains the value 10.0

*/

static float fcn_w_data(float x, void *data)

{

   float *usr_data = (float*)data;

 

   return exp(x) - usr_data[0]*x + usr_data[1];

}


Visual Numerics, Inc.
Visual Numerics - Developers of IMSL and PV-WAVE
http://www.vni.com/
PHONE: 713.784.3131
FAX:713.781.9260