How do I create a function pointer that points to an MATLAB file using LIBPOINTER in the MATLAB Generic DLL interface?

12 views (last 30 days)
I am using the MATLAB Generic DLL interface to load and use my shared library file in MATLAB. One of the functions in this library requires a function pointer as one of its input arguments. This function pointer can serve, for example, to invoke a callback routine at the C level.
I would like to indicate an MATLAB file as the callback routine for this library function. In the same way that the LIBPOINTER function can be used to create pointer objects from MATLAB variables for use with the shared library, I have tried using a construct such as this to achieve that functionality:
fPtr = libpointer('voidPtr',@myMCallback);
...
result = calllib('myshrlib', 'foo', ... , fPtr);
where @myMFileCallback is a handle to myMCallback.m. These attempts did not work.
I would like functionality in MATLAB that allows me to specify an MATLAB file as the callback routine for a C shared library function.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jan 2010
The ability to use shared library functions that have function pointer inputs is not available in MATLAB. There is no way to write a MATLAB function that is compatible with a C function pointer.
To work around this issue, write a C code wrapper MEX-file around the library function in question. The MEX-file would accept from MATLAB all input arguments required by the function excluding those of the function pointer type. The functions to which the pointer arguments will point should be implemented within the body of the C MEX-file.
If you would like a MATLAB function MATLAB file to act as a callback routine for the shared library function, you can use the mexCallMATLAB routine within the function pointed to in your MEX-file. This routine can then invoke your MATLAB file via the function pointer object.
Written below is a simple example on how to implement such a construct in C. Please note that because MATLAB is not thread-safe, implementing such a construct is not recommended in C code that uses multiple threads. Please use this construct in a single-threaded application.
#include "mex.h"
#include "myAPI.h"
// Callback function
void myCallback()
{
/* Other declarations here */
mexCallMATLAB(nlhs, lhs, nhrs, rhs,"myMCallBack");
}
// MEX Gateway
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* Other declarations here */
void (*cbPtr)() = NULL;
cbPtr = myCallback;
// Assume that myAPIRoutine is implemented in myAPI.dll
myAPIRoutine(arg1, arg2, ... , cbPtr);
}

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2008a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!