Using C library, function with fucntion pointer as a parameter.
Show older comments
I want to make use of a C library in MATLAB but one of the main functions that the library requires has as a parameter a pointer function.
The library that I am using is proprietary so I can not share too much info, I'll try to explain it with a simpler library.
The reason I need the function pointer is because the library does not know how to find the square root of a number, so I need to make a function in MATLAB for finding the square root of a number, then pass a pointer to that function to the library using a function. Since other functions in the library need to know how to do the square root of a number it needs this function to be able to use the rest of the library.
Sorry about the wierd example. I hope this is clear enough. And I just wanted to know if this was possible.
Answers (1)
James Tursa
5 minutes ago
Edited: James Tursa
2 minutes ago
I'm assuming your real function is not actually sqrt(), else you would just call a C math library function for this. But my example will use sqrt() per your request.
You will probably need to write a C-function wrapper for your MATLAB function, then pass a pointer to that function. E.g., something like this:
/* mex_example.c
* Bare bones MATLAB function wrapper example.
* Would need extra argument and return checking for production code.
*/
#include "mex.h"
/* This would be the signature from the header for your library */
/* Takes a function pointer as input and returns a double */
double library_function( double (*mfunction)(double) );
/* This is the C-wrapper function that your library function will call */
double myfunction(double x)
{
double y;
mxArray *rhs[1];
mxArray *lhs[1];
rhs[0] = mxCreateDoubleScalar(x);
if( mexCallMATLAB( 1, lhs, 1, rhs, "matlab_sqrt") ) /* callback to MATLAB */
{
mexErrMsgTxt("The MATLAB function callback failed!");
}
y = mxGetScalar(lhs[0]);
mxDestroyArray(rhs[0]);
mxDestroyArray(lhs[0]);
return y;
}
/* The MATLAB gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double y;
y = library_function( myfunction );
plhs[0] = mxCreateDoubleScalar( y );
}
/* This is the function in your library that takes a function pointer */
double library_function( double (*mfunction)(double) )
{
double x = 2.0; /* Example data created here for simplicity */
double y = mfunction( x );
return y;
}
Compiling and running this:
>> mex mex_example.c
Building with 'MinGW64 Compiler (C)'.
MEX completed successfully.
>> mex_example
ans =
1.4142
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!