Passing C/C++ callbacks into the matlab engine - c++

I have a C++ file that:
starts the matlab engine
calls matlab_optimize() (a compiled m file that runs one of matlab optimizers internally)
prints the result
stops the engine and quits
This works fine. I now want to change the second line into
calls 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?

You can use mclCreateSimpleFunctionHandle function from the mclmcrrt.h header to make this feature.
It Ņonverts a function with a prototype void(*) (int, mxArray*, int, mxArray) to the mxArray structure.
You can pass it to the MATLAB side function and call it like general MATLAB functions without any manipulations with mex files.
On the C/C++ side:
void callback(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
<some manipulations with data>;
}
...
//calling the matlab function
matlab_function(mclCreateSimpleFunctionHandle(callback));
On the MATLAB side:
function [] = matlab_function(function)
function(<any variable>)
end

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.

I'd like to thank totoro for his helpful comment, here some more detailed implementation example on C++ side:
void fromMatlabCallback(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
cout << "WOW I'm from Matlab. and it passes me a param: ";
int aa = mxGetScalar(prhs[0]); // it is first param; nrhs tells how many there are
cout << aa << "\n";
}
void InitializingFunc()
{
mxArray *func_ptr = mclCreateSimpleFunctionHandle(fromMatlabCallback);
mxArray *retVal_ptr = NULL;
mlfUntitled(1, &retVal_ptr , func_ptr); //Untitled is name of my main Matlab func
}

If there is a way to do that, I've never seen it. To make matters worse, the Matlab C++ Math Library you reference no longer exists:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/267802

It seems that you can create a c-linkable library from any MATLAB function
(see here). If this works as advertised, I think you should be able to do what you want though in a different way.

Related

Interacting with C++ objects through Mex files

I'm a bit stuck on if my current goal is feasible, and if so, how to do this. I'm hoping to interact with some C++ classes through a Mex file, but I would need the instances of the objects I am accessing to be persistent across calls from different Mex functions. For example, suppose I do the following within an initialization Mex file:
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
size_t nCats = (size_t) *mxGetPr(prhs[0]);
std::vector<Cat> cats;
for(size_t i = 0; i <nCats; i++){
cats[i] = Cat(/* arguments to constructor*/);
}
}
So I've initialized my Cat objects from my external C++ code. Now, later down the line, I need to update info about my Cat objects, so in a different Mex file I have
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
for(size_t i = 0; i < nCats; i++){
cats[i].feed(/*parameters to feed method*/);
}
}
Here are my questions:
How would I make this std::vector persist across calls to different Mex files? There isn't a way to return non-Matlab types from Mex files (that I'm aware of), and Mathworks says that local variables within Mex functions are generally garbage collected when the function returns, which I do not want. How can I call the same std::vector with the stored objects I am interested in across different functions? Or even calls to the same function?
Is there a better way to do this with Matlab? Essentially I'm trying to use Matlab to drive some C++ code, which does the heavy lifting, and then brings it all back to Matlab for analysis. The trouble is that the C++ code is already written, and I need to try to bend Matlab to fit those classes.
Not sure if possible between Mex functions but you can make some things persistent between calls to the same mex routine.
See documentation for:
mexMakeMemoryPersistent
mexMakeArrayPersistent
Also see this answer on the Mathworks site:
How can I make memory persistent between calls to a MEX-file in MATLAB
I have not done this myself so can't give more specific help but this might point you in the right direction.

Matlab function handles and C++ function pointers

Is it possible to make a Matlab function handle compatible with a C++ function pointer? I am trying to call a C++ function from Matlab that takes in a C++ function pointer. For example:
C++:
void Cfunction( C++functionPointer);
Matlab:
function out Mfunction(functionHandle)
out= Cfunction(functionHandle)
Unfortunately I can not post the code because it is confidential. So I want my Matlab program to call a C++ function using calllib(). One of the parameters for the C++ function is a function pointer. In Matlab, I tried using a Matlab function handle as the parameter in callib but this did not work. Therefore, I am having difficulty calling the C++ function from Matlab.
Matlab is saying that the C++ compiler will not accept the Matlab function handle type for its pointer argument.
Thanks
Ok, so, from what I understand, you have a library written in C++ with a function (let me call it functionFromMyCppLibrary) that you nee to run. One of the arguments this function requires is a function pointer.
I'm assuming this function pointer must be a C++ function. If functionFromMyCppLibrary needs to call an arbitrary Matlab function, then my answer does not apply. However there's a Q&A in the Mathworks exchange that you might find helpful: How do I pass function handles to C++ mex function in MATLAB 7.8 (R2009a)?. You will probably need to modify CppFunction below so that it makes Matlab call feval. It gets actually easier if you can hardcode a Matlab function name in CppFunction().
callTheCppThing.cpp:
#include "mex.h"
#include "myCppLibrary.h"
void CppFunction()
{
// The function your C++ library requires as a function pointer
// You could use mexCallMATLAB here to call a Matlab function,
// but it will get trickier if you can't hard-code the name of
// the Matlab function here
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
{
// Process however you need the arguments
functionFromMyCppLibrary(CppFunction);
// Create the output variables and return whatever Matlab needs
}
You can compile with
mex callTheCppThing.cpp
(Add to this command line anything that is required to link this C++ with your library.)
And you call from Matlab with
callTheCppThing
This removes the need of Matlab passing any kind of handle to your C++ library. (If you have no possibility of writing different wrappers in C++, then check the linked Q&A from Mathworks. It's tricky, but possible.)

How to use mexCallMATLAB from c++ with matlab function which gets function handle?

I want to run lsqnonlin which is a matlab optimization function from C++.
From matlab it is called as follows:
lsqnonlin(#(x)funcHandle(x,var1,var2,..),x_initial,[],[],options);
From metlab c++ API I understoodt that mexCallMATLAB is the function I should use to call matlab and get the output
int mexCallMATLAB(int nlhs, mxArray *plhs[], int nrhs,mxArray *prhs[],
const char *functionName);
how do I pass all the arguments to mexCallMATLAB - {funcHandle,var1,var2,..,x_initial,[],[],options}, especially the function handle? I found this "mclCreateSimpleFunctionHandle" function, but I'm not sure how to use it? I have a mexFunction implementation of the funcHandle, and created a mexw64 version of it, I think I should use that somehow..
Thanks

Passing C++ callbacks to matlab engine as function handles without using mex

My project is in C++. I want to use matlab optimization nonlinsq through matlab engine by "eval". I want to pass a function I wrote in C++ in the format of
void func(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[])
to matlab as a function handle without compiling it to mex.
I tried following Passing C/C++ callbacks into the matlab engine for creating a mxArray and then pass it to matlab workspace:
mxArray *fh = mclCreateSimpleFunctionHandle(func);
engPutVariable(engine, "func", fh);
mxDestroyArray(fh);
but the program crashed on the first line with access violation. In the call stack the last call before the violation was
"mclmcrrt8_5.dll!000000000031dacd() Unknown"
What is the problem?..
Asking the MATLAB run-time engine to interpret the C/C++ code is the wrong way to do it (and I'm sure is impossible at this moment). The post you're referring to assumes that the C/C++ code is compiled into a shared object or a dynamically linked library. The mex function itself requires a supported compiler that can be invoked in order to create the .mex file.
TLDR: MATLAB cannot interpret C/C++ code.

C++ --> Matlab -- mexFunction template

I have a rookie request to make, but i'll be very grateful for your help:
Can someone write for me a brief mexFunction template, which I can add the a cpp script, and have the mexFunction inputs and outputs interact with the cpp's functions?
mexFunction(output array, input array)
{
actions to use the C++ functions // a brief explanation
actions to extract the resulting output // a brief explanation
}
I don't quite get C++ syntax yet, and I don't find any of the tutorials out there very helpful (I did the obvious google search:).
I'm trying to evaluate a certain C++ code with matlab, and im kind of in the dark here.
You help is greatly appreciated! :)
There are enough resources available to get started using MEX functions. Yet you wanted to straight away find some answers / links / codes / materials from here (fair idea - sadly you may get down votes). To answer you and get to a good start ::
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
Only one data type in MEX : mxArray (In some ways, this makes life easier, as it reduces the number of data types to you need to
remember, but it does mean that you need to be careful, and not make any assumptions about the format
of the contents of the array.)
To access the data within an mxArray, you need to get a pointer to it
double *a;
a = mxGetPr(phrs[0]);
To check if a given mxArray contains double precision floats, use:
if (!mxIsDouble(prhs[0])) {
mexErrMsgTxt("Input should be double.\n");
}
To give an idea, instead of just referring to some links, I tried to explain you. Hope it helped.
Some references:
How to create mex
Kind of complete reference (pdf file)