compile the my own matlab function to be a C++ library - c++

In my main matlab function, some m functions written by myself and some built-in matlab functions are called. If I use the maltab compiler mcc to compile these called m functions to be a C++ library, and also compile the main matlab function, is it possible that I could call this main function in my C++ scripts ? Or how could I achieve this goal? Is it a must to convert the main matlab function to a C++ function? Any help will be appreciated.
Here is an example to explain my question more clearly:
function y = mymain(m,n)
...
a = randn(m,n);
b = find(a>0);
c = sqrt(b);
d = myfun1(b);
e = myfun2(c); % myfun1 and myfun2 are the subfunctions written by my self
...
% in myfun1 and myfun2, only the matlab build-in functions are called.
% my goal is to get the point that a C++ main function could call this mymain

Related

Matlab legacy_code Tool - Writing a wrapper functio to catch an array

currently I'm trying to use a C/C++ Code based Library in Matlab/Simulink by means of the Matlab legacy_code tool. I am very new to this, please have some patience with me.
I stumbled upon the problem, that I got class members which return an array.
What I did upon now is to follow the Matlab legacy-code examples, especially this one:
Integrate External C++ Object Methods
As far as I can see, the legacy_code tool demands a wrapper function to be wrapped around a method call, so basicaly I could, within this wrapper function manipulate the return value of the called methad any way necessary. This far no problem.
But, I'm not certain how to receive an array of information from the called method an then pass this array to Matlab/Simulink.
e.g. A method's return value is an pointer pointing at an array of information of which, let us assume, we know the length of valid information it holds.
/* Simple example */
uint8_t* BUS::answerRcvd()
{
static int r[10];
int i;
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i)
{
r[i] = rand();
}
return r;
}
Is there a way to create a wrapper function for such a method that would receive an array of information and pass it along to matlab?
Might there be a possibility to handle that array as e.g. single values of uint8_t (if way stay with the given example) and pass these like in an ordinary matlab function?
[a,b,c] = function()
I'm open to any suggestion, thank you very much in advance.
Ok, looks like I found a Solution to my problem.
As a wrapper function its possible to use the following pattern
void myfunc(double u1, double u2, double u3, double *y1, double *y2)
{
*y1=u1;
*y2=(u2+u3)/2;
}
This wrapper function the is then interfaced by the Legacy Code Tool (LCT) as followed:
def = legacy_code('initialize')
def.OutputFcnSpec = 'void myfunc(double u1, double u2, double u3, double y1[1], double y2[1])'
Simple as that. On C/C++ code use pointer nomenclature / syntax, on Matlab use array nomenclature / syntax.
I hope, this will help some people like me who need a solution to interface with legacy code which should not only accept multiple inputs, but multiple outputs as well.
In hindsight the option tuuse pointers is pretty obvious, but if you don't knoe how to teach your LCT how to interface with it, it easily becomes an tiring task.

How do I call a matlab variable from an S function?

I am working on an S function in simulink. There are some variables in the MATLAB workspace available. I want to call them.
So in MATLAB:
a=3;
and in the S function (written in C/C++):
double a = CallFromMATLABWorkSpace(a); //Something like this.
How do I do this? There is something like mexCallMATLAB but it is not clear how I should use this in this situation.
To get data from a workspace use the function mexGetVariable.
However, this is a somewhat unusual thing to do.
Why isn't the data being passed as a parameter to the S-Function?
From what I can see in the documentation for mexCallMATLAB, as well as interoping with C++ source code, it would look something like the following:
Let's say you have a MatLab function MyDoubleFunction that takes a single scalar double value and returns a scalar double value. You would do the following if you wanted to pass the function a value of 4.0 and see what the answer is:
//setup the input args
mxArray* input_args[1] = {mxCreateDoubleScalar(4.0)};
mxArray** output_args; //will be allocated during call to mexCallMATLAB
//make the call to the Matlab function
if (mexCallMATLAB( 1 /* number of output arguments */,
output_args,
1 /* number of input arguments */,
&input_args,
"MyDoubleFunction"))
{
//error if we get to this code block since it returned a non-zero value
}
//inspect the output arguments
double answer = mxGetScalar(*output_args);

How to call a JITed LLVM function with unknown type?

I am implementing a front-end for a JIT compiler using LLVM. I started by following the Kaleidoscope example in the LLVM tutorial. I know how to generate and JIT LLVM IR using the LLVM C++ API. I also know how to call the JITed function, using the "getPointerToFunction" method of llvm::ExecutionEngine.
getPointerToFunction returns a void* which I must then cast to the correct function type. For example, in my compiler I have unit test that looks like the following:
void* compiled_func = compiler.get_function("f");
auto f = reinterpret_cast<int32_t(*)(int32_t)>(compiled_func);
int32_t result = f(10);
The problem is that I have to know the function signature beforehand. In the example above, I have a function "f" which takes takes a 32-bit integer and returns a 32-bit integer. Since I create "f" myself, I know what the function type is, so I'm able to call the JIT'ed function. However, in general, I do not know what the function signature is (or what the struct types are) that are entered by the user. The user can create arbitrary functions, with arbitrary arguments and return types, so I don't know what function pointer type to cast the void* from LLVM's getPointerToFunction. My runtime needs to be able to call those functions (for a Read-Evaluate-Print loop, for example). How can I handle such arbitrary functions from my JIT runtime?
Thanks
There's not much information you get can from compiled_func - as you wrote, it's just a void*. But when you write "in general, I do not know what the function signature is", that's not accurate - you've just compiled that function, so you should have access to the LLVM Function object, which can be queried about its type. It's true that it's an LLVM IR type and not a C++ type, but you can often know which translates to which.
For example, if we borrow code from the tutorial's section on JITting Kaleidoscope:
if (Function *LF = F->Codegen()) {
LF->dump(); // Dump the function for exposition purposes.
// JIT the function, returning a function pointer.
void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
// Cast it to the right type (takes no arguments, returns a double) so we
// can call it as a native function.
double (*FP)() = (double (*)())(intptr_t)FPtr;
fprintf(stderr, "Evaluated to %f\n", FP());
}
Then yes, FPtr was "assumed" to be of type double (), but there's also LF of type Function* here, so you could have done something like:
Type* RetTy = LF->getReturnType();
if (RetTy->isDoubleTy()) {
double (*FP)() = (double (*)())(intptr_t)FPtr;
fprintf(stderr, "Evaluated to %f\n", FP());
} else if (RetTy->isIntegerTy(32)) {
int (*FP)() = (int (*)())(intptr_t)FPtr;
fprintf(stderr, "Evaluated to %d\n", FP());
} else ...
And in much the same way, you can query a function about its parameter types.
A bit cumbersome? You can use your execution engine to invoke the function, via its handy runFunction method, which receives a vector of GenericValues and returns a GenericValue. You should still query the Function type to find what the underlying type under each GenericValue should be.

passing python array to c++ function using ctypes

I'm still new to this kind of extending (though I've a good background in C++ and python)
what I wanted is to use ctypes module to pass data to a C++ function
example that worked so far for me:
test.dll file
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT int sum(int a, int b) {
return a + b;
}
sum_test.py file:
from ctypes import cdll
mydll = cdll.LoadLibrary('test.dll')
mydll.sum(5, 3)
result is 8 which works well...
note:
I'm using this to develop an Addon(plugin) for blender, the data which I will pass to the C++ function is a huge array (Tuple or whatever type of array), this data will be passed to GPU to process it with OpenCL
mainly the workflow in C++ is passing a pointer (which will copy the whole array data to the GPU)
so the question is:
the best way (fastest too) to get that tuple pointer inside C++ (hopefully with explaining what happens in python and in C++)
The easiest way is to tell ctypes that the function takes a pointer to an array of a certain type, in many cases Python/ctypes will figure out the rest.
libc = CDLL('libc.so.6') # on Debian/Linux
printf = libc.printf
printf.restype = c_int
printf.argtypes = [POINTER(c_char), c_int]
printf('< %08x >', 1234)
This assumes that the function will simply take a pointer. If your function takes for example exactly five floats, you could provide c_float * 5 as according parameter type.

input argument structure of compiled matlab function called from c++ [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
compiled matlab file called from c++
I went through the mcc example in MATLAB but something is not clear. Can someone please clarify? In the example we have:
function a = addmatrix(a1, a2) a = a1 + a2;
which after i compile using mcc results in a following definition in the c++ header file
addmatrix(int nargout, mwArray& a, mwArray& a1, mwArray& a2);
My question is if the output of the MATLAB function is a structure which contains a vector of dimension 1x5 and a matrix of dimension 7x3 then what should nargout be? And how should i define mwArray a?
Since the output of the MATLAB function is just 1 structure should nargout be equal to 1? And should I be defining mwArray as mwArray a(1*5+7*3) in my c++ code?
thanks in advance.
You do not explicitly define nargout in your Matlab code. Rather it is defined implicitly by the number of values that your function returns.