Matlab function handles and C++ function pointers - c++

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.)

Related

(MATLAB/C++) Is it possible to pass functions as arguments to C++ MEX functions?

I have only been working with mex functions for a couple of weeks, and am now working on writing a Runge-Kutta, 4th order solver as a C++ mex function.
I am wondering whether it is possible to take a function as an input.
Effectively, it would be nice to have my dynamics function written in MATLAB and pass it straight through to my RK4 mex function.
For example, if the dynamics are governed by Duffing's equation, written in MATLAB:
function xdot = Duffing(t,x)
xdot = [x(2); 0.3*cos(t)-0.22*x(2)+x(1)-x(1)^3];
end
(I do realize this can be written in line as Duffing = #(t,x) (whatever) also)
Is there a way to call the dynamics function from within a mex function or is inputs[] constrained to numeric types only?
I tried the following:
class MexFunction : public matlab::mex::Function {
public:
void operator()(ArgumentList outputs, ArgumentList inputs) {
// Access the dynamics function
typedef TypedArray<double> xdot_type (TypedArray<double>, TypedArray<double>);
xdot_type xdot;
xdot = inputs[0];
Naturally, this doesn't work because inputs[0] is not assignable to 'TypedArray<double> (TypedArray<double>, TypedArray<double>)', since I think the ArgumentList thinks inputs[0] should be purely numeric.
Can anyone think of a solution to this, or will I just have to write my dynamics function in C++?
Looking forward to some suggestions!
Thomas
Just quickly skimming the MATLAB C++ API doc, it looks like you can do this using the matlab::engine::MATLABEngine::feval interface found here:
https://www.mathworks.com/help/matlab/matlab_external/cpp-mex-api.html?searchHighlight=fevalAsync&s_tid=srchtitle#mw_723048ca-e22f-4bfb-aa12-47b8007da774
I.e., pass your function name into the C++ mex file as a string which you can get from the ArgumentList via the matlab::data::CharArray syntax:
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) {
matlab::data::CharArray fname = inputs[0];
etc.
Then convert fname into a std::u16string and use that in the feval interface.
In addition to #James's answer, it is also possible using coder.extrinsic within a thin code-generated wrapper layer that sits between the C++ Mex and your Matlab function.
calls calls
C++ Mex layer ----> Code-Generated Matlab wrapper lib (coder.extrinsic) ----> Matlab function
However, it's probably not a good design. I assume you are using C++ for performance reasons. Pausing the execution of your program, to marshal data from C++ into Matlab is slow. If you are running a time-stepping simulation, you may find the interop code becomes a performance bottleneck. A better design may be to adapt your dynamics equation Matlab code, to make it code-generatable, then you can invoke the C++ directly from the generated C code.

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.

Wrapping c++ code in Matlab to access program state information in Matlab

I have a c++ program that updates a system. When I wrote everything in C++ it looked a little something like this
System S; //initialize a System object 'S'
while (notFinished)
{
S.update1(inputVars1);
S.update2(inputVars2);
}
Now I would like to call the individual update functions from matlab and be able to use access functions (written in c++) to view the state of the program at any time when debugging in matlab.
So matlab will need to call something to instantiate a "System" object, and then it will need to call individual System methods from the original system object.
Suppose I compile separate mex files to Initialize update1 update2 and some that get information about the current state getState. And then write some matlab code...
%matlab main
S = Initalize(); %mex file
while (notFinished)
update1(S); %mex file
keyboard; % access state information using "getState" mex function
update2(S); %mex file
keyboard; % access state information using "getState" mex function
end
Will this essentially allow me to call and debug my C++ program algorithms in Matlab, or is there another way to go about this whole problem?
The way I would do it is by creating a pointer for System in C++ in the Initialize mex function using "new". If you are on a 64 bit platform then cast this pointer to a 64-bit integer and create an mxArray with that type and value. Return this mxArray from your Initialize function.
For later calls to your other mex files you should pass this mxArray as an input. Inside those files you can cast it back as a pointer and call methods on the object.
I also would take one more step to wrap this whole thing inside a MATLAB System object or a regular object and not expose the pointer value S outside the object. You need methods on the object which would call your mex files. This is especially needed if you are planning to give this to other people for use. Others might accidentally overwrite or modify S causing crashes.
Finally you need a delete mex function which would delete the pointer S. If you create a handle class then you can do this in the destructor.

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.