现在的位置: 首页 > 综合 > 正文

Matlab与C/C++混合编程 之 C/C++ Source MEX-Files

2013年10月08日 ⁄ 综合 ⁄ 共 9138字 ⁄ 字号 评论关闭

C/C++ Source MEX-Files

The Components of a C/C++
MEX
-File

You create binary MEX-files using themex buildscript.
mex compiles and links source files intoa 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 of:

Gateway Routine

The gatewayroutine is the entry point to the
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 be mexFunction.

Required Parameters

A gateway routine must contain the parameters prhs, nrhs,
plhs
,and nlhs described in the following table.

ParameterDescription

  • prhs An array of right-hand input arguments.
  • plhs An array of left-hand output arguments.
  • nrhs The number of right-hand arguments, or the size of the prhs array.
  • nlhs The number of left-hand arguments, or the size of the plhs array.

Declare prhs and plhs astype mxArray *, which means they point to MATLAB arrays.They are vectors that contain pointers to the arguments of theMEX-file.

You can think of the name prhs as representingthe "parameters, right-hand side," that is, the inputparameters. Likewise,plhs represents 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 in themex command.

The name of the file containing your gateway routine is important,as explained inNaming the
MEX-File
.

Using MATLAB Libraries

The MATLAB C/C++ and Fortran API Reference describesfunctions 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 include themex header, 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 using themexext function,which returns the value for the current machine.

Computational Routine

The computational routine contains thecode for performing the computations you want implemented in the binaryMEX-file. Computations can be numerical computations as well as inputtingand outputting data. The
gateway calls the 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
mwSize and mwIndex for cross-platform flexibility.mwSize representssize values, such as array dimensions and number of elements.mwIndex representsindex values, such as indices into arrays.

Data Flow in MEX-Files

The following examples illustrate data flow in
MEX
-files:

Showing Data Input and Output

Suppose your MEX-file myFunction has twoinput arguments and one output argument. The MATLAB syntax is[X]= myFunction(Y, Z). To call
myFunction from MATLAB,type:

X = myFunction(Y, Z);

The MATLAB interpreter calls mexFunction,the gateway routine to myFunction, with the followingarguments:

Your input is prhs, a two-element array (nrhs= 2). The first element is a pointer to anmxArray named
Y andthe second element is a pointer to an mxArray namedZ.

Your output is plhs, a one-element array(nlhs = 1) where the single element is anull pointer.The parameter
plhs points at nothing because theoutputX is not created until the subroutine executes.

The gateway routine creates the output array and sets a pointerto it in plhs[0]. If the routine does not assigna value toplhs[0] but you assign an output valueto the function when you call it, MATLAB generates an error.

Note  It is possible to return an output value even if nlhs= 0. This corresponds to returning the result in theansNotevariable.

Gateway Routine Data Flow Diagram

The following MEX Cycle diagram shows how inputs enter a
MEX-file,what functions the gateway routine performs, and how outputs returnto MATLAB.

In this example, the syntax of the MEX-file
func is [C,D] = func(A,B). In the figure, a call to func tells MATLAB topass variables
A and B to yourMEX-file.
C and D are left unassigned.

The gateway routine func.c uses the mxCreate* functionsto create the MATLAB arrays for your output arguments. It sets
plhs[0] and plhs[1] tothe pointers to the newly created MATLAB arrays. It uses the
mxGet* functionsto extract your data from your input arguments prhs[0] and
prhs[1].Finally, it calls your computational routine, passing the input andoutput data pointers as function parameters.

MATLAB assigns plhs[0] to C and plhs[1] to D.

C/C++ MEX Cycle


MATLAB Example yprime.c

Look at the example, yprime.c, found in your matlabroot/extern/examples/mex/ folder.(Building
MEX-Files
explains how tocreate the binary
MEX-file.) Its calling syntax is [YP] =YPRIME(T,Y), where
T is an integer and Y isa vector with four elements. For T=1 and
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 includes 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 of the mxCreate* functions, like
mxCreateDoubleMatrix
, mxCreateSparse, or
mxCreateString
. If it needs them,the gateway routine can call
mxCalloc
toallocate 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 in mxArray and manipulate it in your computational subroutine. For example, theexpression
mxGetPr(prhs[0]) returnsa pointer of type double * to the real data inthe
mxArray pointed to by prhs[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
mxArray to 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 the
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 .cpp file extension. The extension
.cpp isunambiguous 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, at

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.

Use mex -setup to 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++ illustrate the use of C++ by walkingthrough source code examples available in your MATLAB folder.

Memory Considerations For Class Destructors

Do not use the mxFree or mxDestroyArray functionsin a C++ destructor of a class used in a
MEX-function. If the
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 cancorrupt memory.

Use mexPrintf to Print to the MATLAB Command Window

Using cout or the C-language printf functiondoes not work as expected in C++
MEX-files. Use the mexPrintf function instead.

Matlab->User's Guide->External Interfaces->Creating C/C++ Language MEX-Files->C/C++ Source MEX-Files

抱歉!评论已关闭.