I have a C++ file that:
matlab_optimize()
(a compiled m file that runs one of matlab optimizers internally)This works fine. I now want to change the second line into
matlab_optimize(obj_fun)
Where obj_fun()
is a function defined in my C++ code which itself will callback into other code. Essentially I want the matlab optimizer used internally in matlab_optimize
to use my supplied function pointer as the objective function.
I cant just compile obj_fun()
as a standalone mex file since I want it to communicate with the c++ process that starts the matlab engine (which drives the whole thing).
A newsgroup post from 2009 seems to indicate this is not possible. Then again the Matlab C++ Math Library Toolbox does seem to be able to do this.
Googling around also reveals this generated snippet:
/*
* Register a function pointer as a MATLAB-callable function.
*/
extern void mexRegisterFunction(void);
Which seems exactly what I want but the file is from 2000, and I find no reference to this function in the matlab docs anywhere. So how to use this?
I contacted Mathworks about the issue and managed to get it all working. This question was part of a wider effort of being able to pass callbacks to Python functions directly to Matlab.
Full details on this blog post and code available on github.