
5.4 Simple C++ Template for a MATLAB Library
In the following we show a template for a wrapper-class for simply including compiled
MATLAB source code into an existing system. Listing 5 is a scratch of a simple main
function that calls a constructor, runs a function defined within the wrapper class and
finally calls a destructor. The class according to the created instance is given by Listing 6.
The main advantage of using such structure is that the programmer at C++ level must
not have any knowledge about the MATLAB-world. Initializing and destructing the
MATLAB-environment, converting the data to the correct format and calling functions
of the MATLAB C/C++ API is done within the wrapper-class. The same thing can be
done within only one C-function as well, but therefore the MATLAB environment has to
be initialized every time the function is called. For return values call by reference is used,
since the MATLAB functions often return more than one parameter. This is not a must,
but would be easier.
#in c lu d e " wrapper . h"
i n t main ( i n t argc , char * argv [])
{
// create the component
Temp late _ Comp onen t * pComp = new Te mpla te_C o mpon ent ();
// create the matrices in C- style
i n t Dim1 = 2; i n t Dim2 = 3;
double Matrix [2][3] = {{1 ,2 ,3} ,{4 ,5 ,6}};
double Result [2][3] = {0 ,0 ,0 ,0 ,0 ,0};
// call the service
pComp -> su bscri b e_dem o (( double *) Matrix , Dim1 , Dim2 , (double *) Result 1 );
...
// display the result in C - style
printf (" S ourcem a trix :\ n " );
printf (" %f %f %f\ n" , Matrix [0][0] , Matrix [0][1] , Matrix [0][2]);
printf (" %f %f %f\ n\ n " , Matrix [1][0] , Matrix [1][1] , Matrix [1][2]);
printf (" Result Matrix :\ n" );
printf (" %f %f %f\ n" , Result1 [0][0] , Result1 [0][1] , Result1 [0][2]);
printf (" %f %f %f\ n\ n " , Result1 [1][0] , Result1 [1][1] , Result1 [ 1 ][2]);
...
// delete the component
d e l e t e pComp ;
return 0;
}
Listing 5: main.cpp
17
Komentarze do niniejszej Instrukcji