C++ --> Matlab -- mexFunction template - mex

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)

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.

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.

IOS code has become very slow because of objc_msgSend

I have rewritten part of my code from very simple c arrays to using (or trying to use) objects in order to get more structure into it. Instead of passing arrays through the function header I am now using a global array defined by a singleton. You can see an example of a function in my code below:
it was:
void calcdiv(int nx,int ny,float **u,float **v,
float **divu,float dx,float dy,float **p,
float dt,float rho, float **bp,float **lapp)
{
int i,j;
for (i=2;i<=nx-3;++i){
for (j=2;j<=ny-3;++j){
divu[i][j] = (u[i+1][j]-u[i-1][j])*facu +
(v[i][j+1]-v[i][j-1])*facv;
}
}
...
now it is:
void calcdiv()
{
int i,j;
SingletonClass* gV = [SingletonClass sharedInstance];
for (i=2;i<=gV.nx-3;++i){
for (j=2;j<=gV.ny-3;++j){
gV.divu[i][j] = (gV.u[i+1][j]-gV.u[i-1][j])*facu +
(gV.v[i][j+1]-gV.v[i][j-1])*facv;
}
}
...
Before the restructuring I have been using the function call as given above. That means passing the pointers to the arrays directly. Now I access the arrays by the singleton call "SingletonClass* gV...". It works very fine except the fact that it is much slower than before. The profiler tells me that my program spends 41% of the time with objc_msgSend which I have not had before.
From reading through the posts I have understood that this probably can happen when msgSend is called very often. This is then most likely the case here, because my program needs a lot of number crunching in order to display an animated flow with OpenGl.
This leads me to my question: What would you suggest? Should I stay with my simple C implementation or is there a rather simple way to accelerate the objective c version? Please be patient with me since I am new to objective c programming.
Any hints and recommendations are greatly appreciated! Thanks in advance.
If your straight C method works fine, and your Objective C method puts you at a disadvantage due to method calling, and you need the performance, then there's no reason not to use straight C. From looking at your code, I don't see any advantage to whatever "structure" you're adding, because the working code looks almost precisely the same. In other words, Obj-C doesn't buy you anything here, but straight C does, so go with what's best for your user, because in terms of maintainability and readability, there's no difference in the two implementations.

Passing C/C++ callbacks into the matlab engine

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.