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

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

Related

Explaining C++ (C Binding Library) Function

I'm trying to understand a Function/Method in a Library in order to port it to Java however some parameters don't make any sense to me and reading the source code the library is based on is not helping.
Function (Note the API has few comments (We can also ignore the calc handle since it's got a supplier method))
Ssr calc_ssr(CalcHandle *calc, NoteInfo *rows, size_t num_rows, float music_rate, float score_goal) {
std::vector<NoteInfo> note_info(rows, rows + num_rows);
auto skillsets = MinaSDCalc(
note_info,
music_rate,
score_goal,
reinterpret_cast<Calc*>(calc)
);
return skillset_vector_to_ssr(skillsets);
}
NoteInfo Struct
struct NoteInfo
{
unsigned int notes;
float rowTime;
};
MinaSDCalc
// Function to generate SSR rating
auto
MinaSDCalc(const std::vector<NoteInfo>& NoteInfo,
const float musicrate,
const float goal,
Calc* calc) -> std::vector<float>
{
if (NoteInfo.size() <= 1) {
return dimples_the_all_zero_output;
}
calc->ssr = true;
calc->debugmode = false;
return calc->CalcMain(NoteInfo, musicrate, min(goal, ssr_goal_cap));
}
Calc expected input file data (Only care about the #Notes: ...)
Pastebin
Question
What is NoteInfo in calc_ssr, I don't know any C or C++ so the *rows to me just seems like a pointer to a Noteinfo instance, however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me (pairing this with the fact that NoteInfo needs another parameter rowTime which I think is time of Note occurrence in the file which means that value must not be constant otherwise the produced result would be inaccurate)
Github Project: https://github.com/kangalioo/minacalc-standalone (The code alone may not explain enough but it's worth a try; best to look at API.h and discern what's used from there. Though I do warn you a lot of the Code is esoteric)
Sorry if this doesn't make much sense but I've been looking into this since June/July and this API is the closest abstraction from the bare C++ code I could find.
NoteInfo * rows here is pass by pointer. So, rows actually is a pointer to an instance of type NoteInfo. This is one of the ways to pass arrays in c++ to a function. Since arrays are contiguous in memory so we can just increment the pointer by one and get the next element of the array.
for example look at these three ways to do exactly one thing, parameter to pass an array to a function :-
1. void myFunction(int *param) {}
2. void myFunction(int param[10]) {}
3. void myFunction(int param[]) {}
Look into this link for more understanding : https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm
Also search for pass by pointer and pass by reference to look into different ways of passing arguments in c++.
2.however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me: as to this question of yours, you can now see MinaSDCalc is actually getting an array and not a single instance as passing the pointer is also one of the ways of passing an array in c++.

Assure that parameters passed to a function are unique

I have a function that looks like this, that calls a function from a third party dll:
void f1(const double * const input, double * output){
// this function will modify output[]
// I have no knowledge of the implementation of this function, only that it wants
// 3 doubles as the input parameters, and it will modify the last 3 parameters to
// pass the result to me.
call_to_third_party_dll(input[0], input[1], input[2], output[1], output[2], output[3]);
}
I am calling this function like this:
double value[3] { 1, 2, 3 };
f1(value, value);
// value is now modified
This works, and gives the expected results. (It modifies 'value' as expected.)
I am calling the function with the same pointer for both parameters because it is convenient in the calling context, but I have questioned whether this is safe to do, since I don't know how 'call_to_third_party_dll' handles the parameters. (for example, it might modify one of the 'output' parameters, then use the modified value as an input for a subsequent calculation.)
I would like to construct f1 in a way that the compiler would complain if 'input' and 'output' are the same thing (like my example).
Is there a way to construct f1 so that it can fail at compile time if 'input' and 'output' are pointing to the same thing?
Note, f1 would not have to use double *. Whatever is passed will have to resolve to 3 doubles for the input parameters to the third party dll, and 3 doubles for the output of the third party dll.
No, you can't have such a check at compile time. There are other options you have though, which are done at runtime.
Make a copy of the input. That way, you won't ever get in a situation where you change the same memory. This is of course not very useful if the array is big, but if the array is only 3 doubles, it's no big deal.
Compare the pointers. If the pointers points to the same memory, raise an error. You should also make sure that the pointer with the lower address is at least n * sizeof(type) bytes away from the pointer with the higher address. I'm unsure if this is a good solution, but it might be a "good-enough" protection for debugging.
You change your function to:
std::array<double, 3> f1(std::array<double, 3> input){
std::array<double, 3> output;
call_to_third_party_dll(input[0], input[1], input[2], output[1], output[2], output[3]);
return output;
}
You can be sure that input and output are distinct objects.

Explaining Pass by Pointer in C++?

I have a C++ function in which I have two int's, who's purpose is to serve as counters, that are declared outside of the function in my main code. My goal is to update the counter variables with the result from the execution of the function.
I have them declared as such
int cor_letters = 0;
int cor_place = 0;
and then call my function like
res = compare(input, secret_word, &cor_letters, &cor_place);
My compare function header is:
bool compare(string user_input, string secret, int * correct_letters, int * correct_place)
and in my compare code, when I get the final values of the counters, I update them as such:
correct_letters = &cor_l;
correct_place = &cor_p;
I arrived at this solution after carefully reading through my compiler errors, and this seems to work. However, I don't quite understand why this works. In the beginning, I take the address of the two variables and pass them into the function. But the function takes two pointers. So the pointers point to the address of the passed in variables.
Up to this point I seem to grasp what's going on. But its the final assignments that I'm confused by - the pointers (note they're the var names from the function header) are then being updated to the address of the temporary inner function variables that I'm using. Why does this get me the values?
I'm more of a visual learner, and pointers are hard to grasp by just reading some text, so if you wouldn't mind making some quick text diagram to represent what's going on, that would be great. Thank you
I guess you ended up with
correct_letters = &cor_l;
correct_place = &cor_p;
in order to make the compiler stop complaining.
Your analyse about taking the address of local variable is correct.
You probably want to do this
*correct_letters = cor_l;
*correct_place = cor_p;
in order to assign the correct values to the variables
which are outside the function.
A brief memo about reference (&) and dereference (*) operations.
TYPE var_a=..., var_b=...; // some variables of a chosen type
TYPE *ptr=NULL; // a pointer on such a type, but not referencing anything yet
ptr=&var_a; // now ptr memorises the address of var_a (reference operation)
var_b=*ptr; // access the value which is stored at the address memorised
// by ptr (dereference operation) in order to read it
// (here, this has the same effect as var_b=var_a; )
*ptr=var_a+var_b; // access the value which is stored at the address memorised
// by ptr (dereference operation) in order to alter it
// (here, this has the same effect as var_a=var_a+var_b; )

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 to check return value of a function in Lauterbach(Trace32)?

I need to check the return value of a function from a TRACE32 script.
Reading the documentation I see a possible solution to read Program Counter(IP) register and then after executing the instruction at address where PC points to take the value from there.
Is there any other function which returns directly the value returned by a function ?
Every function has usually a pseudo-variable called "return". You can see that in window sYmbol.Browse.Var \\*\*\<myfunc>\* (where myfunc is the name of your function)
Of any variable you can get its value with PRACTICE function Var.VALUE(<variable>).
So you get the return value of function myfunc() with
GO sYmbol.EXIT(myfunc) // go to return statement of myfunc
PRINT Var.VALUE(return) // get the return value
If you'd like to do a module test, another approach might be interesting for you: So imaging you just want to call the function int func3(int a, int b) with random arguments (e.g. 5 and 3) and get the return value. In this case, do the following:
Var.NEWLOCAL \x // create artificial variable on the PRACTICE stack
Var.Set \x=func3(5,3) // execute func3() with arguments 5 and 3 on your CPU
PRINT Var.VALUE(\x) // get the return value