Mixed Programming of MATLAB and C/C ++: C/C ++ source Mex-Files

Source: Internet
Author: User
Tags file handling
C/C ++ source Mex-filesthe components of a C/C ++
Mex-File

You create Binary Mex-files usingMEXBuildscript.
MEXCompiles and links source files within a shared library called a binarymex-file, which you can run at the MATLAB CommandLine. Once compiled, you treat binarymex-Files
Like MATLAB functions.

This section explains the components of a source
Mex-file, statementsyou use in a program source file. Unless otherwise specified, theterm "Mex-file" refers to a source file.

The Mex-file consists:

  • A gateway routine thatinterfaces C/C ++ and Matlab data.
  • A computational routine writtenin C/C ++ that performs the computations you want implemented in thebinarymex-file.
  • Preprocessor macros forbuilding platform-independent code.
Gateway routine

TheGatewayroutineIs the entry point to
Mex-file shared library. It is through this routine that MATLAB accesses the rest of theroutines in yourmex-files. Use the following guidelines to createa gateway routine:

He following is a sample C/C ++ Mex-file gateway routine:

void mexFunction(    int nlhs, mxArray *plhs[],    int nrhs, const mxArray *prhs[]){   /* more C/C++ code ... */}
Naming the gateway routine

The name of the gateway routine must beMexico Function.

Required Parameters

A gateway routine must contain the parametersPrhs,Nrhs,
Plhs
, AndNlhsDescribed in the following table.

Parameterdescription

  • PrhsAn array of right-hand input arguments.
  • PlhsAn array of left-hand output arguments.
  • NrhsThe number of right-hand arguments, or the size ofPrhsArray.
  • NlhsThe number of left-hand arguments, or the size ofPlhsArray.

DeclarePrhsAndPlhsAstypeMxarray *, Which means they point to MATLAB arrays. They are vectors that contain pointers to the arguments of themex-file.

You can think of the namePrhsAs representingthe "parameters, right-hand side," that is, the inputparameters. Likewise,PlhsRepresents the "parameters, left-hand side," or output parameters.

Creating and using source files

It is good practice to write the gatewayroutine to call a computational routine; however, this is not required. the computational code can be partof the gateway routine. if you use both gateway and computationalroutines, you can combine them
Into one source file or into separatefiles. If you use separate files, the gateway routine must be the first source file listed inMEXCommand.

The name of the file containing your gateway routine is important, as explained innaming
Mex-file.

Using MATLAB Libraries

TheMatlab c/C ++ and FORTRAN api referenceDescribesfunctions you can use in your gateway and computational routines thatinteract with MATLAB programs and the data in the MATLAB workspace. The MX matrix library functions provide access
Methods for manipulating MATLAB arrays. the Mex library functions perform operations in the MATLAB environment.

Required header files

To use the functions in the C/C ++ and fortran api referencelibrary you must includeMEXHeader, whichdeclares the entry point and interface routines. Put this statementin your source file:

#include "mex.h"
Naming the Mex-File

The binary Mex-file name, and hence the name of the functionyou use in MATLAB, is the name of the source file containingyour gateway routine.

The file extension of the binary Mex-file is platform-dependent.You find the file extension usingMexextFunction, which returns the value for the current machine.

Computational routine

TheComputational routineContains thecode for creating the computations you want implemented in the binarymex-file. Computations can be numerical computations as well as inputtingand outputting data.
Gateway callthe computational routine ASA subroutine.

The programming requirements described in creating and using source files, using Matlab libraries, and
Required header files might also apply to your computationalroutine.

Preprocessor macros

The mxmatrix and Mex libraries use the MATLABPreprocessormacros
MwsizeAndMwindexFor cross-platform flexibility.MwsizeRepresentssize values, such as array dimensions and number of elements.MwindexRepresentsindex values, such as indices into arrays.

Data Flow in Mex-Files

The following examples analyze strate Data Flow in
Mex-files:

  • Showing data input and output
  • Gateway routine data flow digoal
  • MATLAB example yprime. c
Showing data input and output

Suppose your Mex-FileMyfunctionHas twoinput arguments and one output argument. The MATLAB syntax is[X] = myfunction (Y, Z). To call
MyfunctionFrom MATLAB, type:

X = myFunction(Y, Z);

The MATLAB interpreter CILSMexico Function, The gateway routineMyfunction, With the followingarguments:

Your input isPrhs, A two-element array (Nrhs = 2). The first element is a pointer toMxarrayNamed
YAndthe second element is a pointer toMxarrayNamedZ.

Your output isPlhs, A one-element array (Nlhs = 1) Where the single element isNullPointer. The Parameter
PlhsPoints at nothing because TheoutputXIs not created until the subroutine executes.

The gateway routine creates the output array and sets a pointerto it inPlhs [0]. If the routine does not assigna valuePlhs [0]But you assign an output valueto the function when you call it, Matlab generates an error.

NoteIt is possible to return an output value even ifNlhs = 0. This corresponds to returning the result inAnsNotevariable.

Gateway routine data flow digoal

The following Mex cycle dimo-shows how inputs enter
Mex-file, what functions the gateway routine performs, and how outputs returnto Matlab.

In this example, the syntax of the Mex-File
FuncIs[C, d] = func (A, B). In the figure, a callFuncTells MATLAB topass Variables
AAndBTo yourmex-file.
CAndDAre left unassigned.

The gateway routineFunc. cUsesMxcreate *Functionsto create the MATLAB Arrays for your output arguments. It sets
Plhs [0]AndPlhs [1]Tothe pointers to the newly created MATLAB arrays. It uses
Mxget *Functionsto extract your data from your input argumentsPrhs [0]And
Prhs [1]. Finally, it callyour computational routine, passing the input andoutput data pointers as function parameters.

MATLAB assignsPlhs [0]ToCAndPlhs [1]ToD.

C/C ++ Mex cycle


MATLAB example yprime. c

Look at the example,Yprime. c, Found in yourMATLAB Root/Extern/examples/MEX/Folder. (Building
Mex-files explains how tocreate the binary
Mex-file.) its calling syntax is[YP] = yprime (T, Y), Where
TIs an integer andYISA vector with four elements.T = 1And
Y = 1:4, When you type:

yprime(T,Y)

MATLAB displays:

ans =     2.0000   8.9685   4.0000    -1.0947

The gateway routine validates the input arguments. This step implements des checking the number, type, and size of the inputarrays as well as examining the number of output arrays. If the inputsare not valid, call
Mexerrmsgidandtxt. For example:

/* Check for proper number of arguments */if (nrhs != 2) {mexErrMsgTxt("Two input arguments required.");} else if (nlhs > 1) {mexErrMsgTxt("Too many output arguments.");}/* Check the dimensions of Y.  Y can be 4 X 1 or 1 X 4. */m = mxGetM(Y_IN);n = mxGetN(Y_IN);if (!mxIsDouble(Y_IN) || mxIsComplex(Y_IN) ||   (MAX(m,n) != 4) || (MIN(m,n) != 1)) {mexErrMsgTxt("YPRIME requires that Y be a 4 x 1 vector.");}

To create MATLAB arrays, call one ofMxcreate *Functions, like
Mxcreatedoublematrix,Mxcreatesparse, Or
Mxcreatestring. If it needs them, the gateway routine can call
MxcallocToallocate temporary work Arrays for the computational routine. In thisexample:

/* Create a matrix for the return argument */ plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL); 

In the gateway routine, you access the data inMxarrayAnd manipulate it in your computational subroutine. For example, theexpression
Mxgetpr (Prhs[0])Returnsa pointer of TypeDouble *To the real data inthe
MxarrayPointed toPrhs[0]. You can then use this pointer like any other pointer of Type
Double *In C/C ++. For example:

/* Assign pointers to the various parameters */ yp = mxGetPr(plhs[0]);

In this example, a computational routine,Yprime, Performs the calculations:

/* Do the actual computations in a subroutine */yprime(yp,t,y); 

Aftercalling your computational routine from the gateway, you can set apointer of Type
MxarrayTo the data it returns. MATLAB recognizesthe output from your computational routine as the output from thebinary
Mex-file.

Whena binary Mex-file completes its task, it returns control to MATLAB. MATLAB automaticallydestroys any arrays created by
Mex-file not returned through theleft-hand side arguments.

In general, we recommend that Mex-file functionsdestroy their own temporary arrays and free their own dynamicallyallocated memory. It is more efficient to perform this cleanup inthe Source
Mex-file than to rely on the automatic mechanism.

Creating C ++ Mex-Files

Mex-files support all c ++ language standards.

This section discusses specific c ++ language issues to considerwhen creating and using
Mex-files.

Creating your c ++ source file

The C ++ source code for the examples provided by MATLAB usethe. CppFile extension. The extension
. CppIsunambiguous and generally recognized by C ++ compilers. Other possibleextensions include
. C,. CC, And. Cxx.

For information on using C ++ features, see Technical Note 1605, Mex-files guide,

Http://www.mathworks.com/support/tech-notes/1600/1605.html. Look for the sections under the "C ++
Mex-Files "heading.

Compiling and linking

You can run a C ++ Mex-file only on systems with the same versionof MATLAB that the file was compiled on.

UseMEX -SetupTo selecta C ++ compiler, then type:

mex filename.cpp

You can use command-line options, as shown in the Mex script switches table.

Your link command must have all the necessary DLL files thatthe
Mex-function is dependent upon. To help you check for dependentfiles, see the troubleshooting topic
DLL files not on path on Microsoft Windows systems.

Examples

The examples using C ++ features in
Mex-files and file handling with C ++ using strate the use of C ++ by using ingthrough source code examples available in your MATLAB folder.

Memory considerations for class Destructors

Do not useMxfreeOrMxdestroyarrayFunctionsin a c ++ destructor of a class used in
Mex-function. If
Mex-functionthrows an error, Matlab cleans up
Mex-file variables, as describedin automatic cleanup of temporary arrays.

If an error occurs that causes the object to go out of scope, Matlab callsthe C ++ destructor. freeing memory directly in the Destructor meansboth MATLAB and the Destructor free the same memory, which canw.upt memory.

Use mexprintf to print to the MATLAB command window

UsingCoutOr the C-languagePrintfFunctiondoes not work as expected in C ++
Mex-files. UseMexprintfFunction instead.

MATLAB-> User's Guide-> external interfaces-> creating C/C ++ language Mex-files-> C/C ++ source Mex-Files
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.