Matlab中mex与C混合编程总结

上一篇 / 下一篇  2012-09-05 10:00:28 / 个人分类:C++

 使用mex和C可以加快算法的运行速度,mex文件包含一个入口函数如下:

`*@d)IUp0  void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[] )

\,W]B(c;u p0

-g5l#o[Q5N4RGG0  入口函数有四个参数:prhs为mxArray结构体类型的指针数组,该数组的元素按顺序指向所有的输入参数;51Testing软件测试网 j3b5Y P?_j,q'p

;L.N-Id.K*d|.QR7pu0  nrhs为整数类型,它标明了输入参数的个数。

4uGtl;N0

k,k JO9b2j&j1Eq E?&w0  plhs:为mxArray结构体类型的指针数组,该数组的元素按顺序指向所有的输出参数;

#qoN$En x8B!s0 51Testing软件测试网 i0nF C$n$J `(d[

  nlhs:输出参数的个数

7O!U,v4D`7c)~%v]&J g d C0 51Testing软件测试网,}yA#_"H~

  在入口程序完成两件事情:

,Z&l['LG7S3O;Q0

Ez U"Fg9N,U0  第一:从输入的mxArray结构体中获得计算完毕的数据,然后在用户的子程序中加以使用

Kk I_Ob0

OBp `D)cX)qn0  第二:用户可以将计算完毕的结果返回给一个用于输出的mxArray结构体。

ntlf2C K6A6]'OW0

n?$`%w)F(AAY0  mex源文件的两个组成部分可以分为两个文件也可以放在一个文件中,必须包含mex.h头文件,该头文件包含matrix.h和一些以mex开头的子函数。

0PJ+tKOX^J0

Y/l*^5a"VU'^p0  下面举几个例子:51Testing软件测试网 wC^$HIE-a

51Testing软件测试网e G:F\ |.J.v;j Z

51Testing软件测试网+y"j9H&f2coA&z

51Testing软件测试网\`jqC5^!D

#include "mex.h"
~ }?Ld0Ec1@0/* 输入参数 */
51Testing软件测试网c Ct k&w T&M-ve

j~8j D)ZH0
8y9E$eUxrH0#define MInput prhs[0]     51Testing软件测试网k5N+P(n2L G
/* 输出参数 */

2io` AT5FEQ0 51Testing软件测试网&@1QeS}0I{[

51Testing软件测试网7o8?3q e%o`&es
#define OUTM plhs[0]

(d0y'e^R(Q3A2K0 51Testing软件测试网Sp't)cH(O;N

51Testing软件测试网9bF*N4m't`
void mexFunction( int nlhs, mxArray *plhs[],
V^1? y,Q0      int nrhs, const mxArray *prhs[] ) 51Testing软件测试网5b)@#qAa
         {
4Akp_2h:d0            int i,j,N,L;
9f&PJk:?#}0            double *Input,*output;
.oG0a.D+N)PM.cL/I0  
1YG;Qg$?0         if (nrhs < 1) 
d*O3Q+{](rtr]"F0         {
Djv5E:^0    mexErrMsgTxt("至少需要一个参数!");
)l1d"M le0           }51Testing软件测试网[Xo*DZ$[)p
        Input= mxGetPr(MInput); /*获取矩阵*/ 
^uF*~\]'u(F+o0N = mxGetM( MInput ); /*获取矩阵的行*/51Testing软件测试网5h\$Rs)O
L = mxGetN( MInput); /*获取矩阵的列*/51Testing软件测试网;J:B8XaX+NN7H
for( i=0;i<N;i++) /*一行一样输出*/51Testing软件测试网M`B@;| K J-E
{51Testing软件测试网sbw/x}8]
    for ( j=0;j<L;j++)
U&d!D)N6u+P2j%o-e0     printf("%f ", Input[i+j*N]);/*若索引从1开始则变成i-1+(j-1)*N MATLAB 是按列存数据 */
jZC*t|0          printf("\n"); /*输出完一行,换行*/51Testing软件测试网8r$H'G4Q8x'PfP$h:j$f,X
}
4jQQ#_K%q{r0   
|'p5G#d8UF o o[0 OUTM= mxCreateDoubleMatrix(N,L, mxREAL); /* 建立输出矩阵*/51Testing软件测试网$d8Ee$i'e D.\
 output=mxGetPr(OUTM);51Testing软件测试网8p+l)Lv%v4hA.q
  for( i=0;i<N;i++) /*一行行的赋值*/
%xr?$bu9A0{
Q4Noj d!q Q6~7C Q0    for ( j=0;j<L;j++)51Testing软件测试网h,R:aH's
    output[i+j*N]=Input[i+j*N];/*若索引从1开始则变成i-1+(j-1)*N*/
)\&s]5xRF;O ZLk8}0        51Testing软件测试网+Nm'HMz_
}
/y8Fn DS0hv cYx0  }

&hG dM'J0d Vf051Testing软件测试网RQZa T^1uw

  下面是字符串的操作:

N9g6W ePO#Cw0

4t(z^_cUGWv0 51Testing软件测试网 U1bA~"Xj

51Testing软件测试网m-G(Gk6Aa g~/z

#include "mex.h"51Testing软件测试网|i @3uk u"hA
  
.U{9f,H0QBp&b,D0void51Testing软件测试网p Yw5b/VMG%reR
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
0D,b Bha9xu)KHo0{51Testing软件测试网;g"J T0{-M
    char *buf;51Testing软件测试网 y(y? py9\;~!I$YN
    mwSize buflen;51Testing软件测试网Hyi&b5iaf
    int status;
51Testing软件测试网rT:{R\

51Testing软件测试网 i[([sEl4k4FGP

    (void) plhs;    /* unused parameters */
N8B.VBLS u0   
6dCJS-[#G(Dz0    /* Check for proper number of input and output arguments */
i8S6I#P+|ko0    if (nrhs != 1) {
8U4V&\%l;enT2]0 mexErrMsgTxt("One input argument required.");
1l(X0Kdww0    } 51Testing软件测试网9Xn-F Z(M{
    if (nlhs > 1) {51Testing软件测试网)i*|gHLy0SV
 mexErrMsgTxt("Too many output arguments.");51Testing软件测试网*y*k kjN4]rq;W
    }51Testing软件测试网"ah!L(\&["F%oIT
    51Testing软件测试网*RW S8H}V5ni
    /* Check for proper input type */51Testing软件测试网D9ImA T?
    if (!mxIsChar(prhs[0]) || (mxGetM(prhs[0]) != 1 ) )  {
2_N}PA(w y0 mexErrMsgTxt("Input argument must be a string.");51Testing软件测试网Na^8js:sr \
    }51Testing软件测试网4R7UQ^Rh%P
    51Testing软件测试网v/N9`\.U/wsE
    /* Find out how long the input string is.  Allocate enough memory
#S2Y_qEig)R5ee0       to hold the converted string.  NOTE: MATLAB stores characters51Testing软件测试网1?$Q&Yp{X
       as 2 byte unicode ( 16 bit ASCII) on machines with multi-byte51Testing软件测试网1aV G8]J;RJ{:P*z
       character sets.  You should use mxChar to ensure enough space51Testing软件测试网$E&x*aI@
       is allocated to hold the string */51Testing软件测试网w_/?{S Y
    51Testing软件测试网`k9}wJd
    buflen = mxGetN(prhs[0])*sizeof(mxChar)+1;
G+DMOod{1z0    buf = mxMalloc(buflen);
&mVe!o_0   
1Rb"g3|a0    /* Copy the string data into buf. */
v {r\x"DF,V@ g'x0    status = mxGetString(prhs[0], buf, buflen);   51Testing软件测试网 PwR+N6k2X:]
    mexPrintf("The input string is:  %s\n", buf);51Testing软件测试网@P^Ty!L$Z\
    /* NOTE: You could add your own code here to manipulate
qs;cRd1f0       the string */51Testing软件测试网xk9YX3Io(wZ-}
    51Testing软件测试网5rC9m]6D$?3iu*T
    /* When finished using the string, deallocate it. */51Testing软件测试网0Gh;r3w|HJ:r`
    mxFree(buf);
`$J6x|OL)~0    51Testing软件测试网7a'F'w p2b kNj
}
51Testing软件测试网@.c.RBg8U0s v

'P.m1V!E5m+f*V(h?0  动态分配内存的例子:

VH;p3F+g8Z0

w0e]{v0 51Testing软件测试网7l@TJ%I,?(a;`!hD

51Testing软件测试网:Mq8|On [P,DD

#include "mex.h"

:rZ"l~~0 51Testing软件测试网*xP1Fx3Z o$a [

/* The mxArray in this example is 2x2 */51Testing软件测试网Q$L/o+fKU
#define ROWS 2
6^j{c1qK)e9n$p B-i0#define COLUMNS 251Testing软件测试网E2f[^EG"J1iK L
#define ELEMENTS 4

f2S"ee^"AC3]0 51Testing软件测试网 V)Z;n`HU/Ogr"A

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {51Testing软件测试网4E5LW5mANE(Q?
    double  *pointer;          /* pointer to real data in new array */51Testing软件测试网bD*p I/H'oC0L1J$D\ GM
    double  *dynamicData;      /* pointer to dynamic data */51Testing软件测试网y_w*y%\Xx
    const double data[] = {2.1, 3.4, 2.3, 2.45};  /* existing data */51Testing软件测试网Z9s-f7V*iF F
    mwSize index;
51Testing软件测试网6u [u"{qh@.ri

51Testing软件测试网 b.U7m\4u7TS0@.x

 /* Check for proper number of arguments. */51Testing软件测试网 L/L*MyOc1j
    if ( nrhs != 0 ) {
$Sp k;C!{ I:g;u0        mexErrMsgIdAndTxt("MATLAB:arrayFillGetPrDynamicData:rhs","This function takes no input arguments.");51Testing软件测试网L9k+U E{|Y
    }
51Testing软件测试网~7q)Z [Kyr&Q-n

51Testing软件测试网0~z:E!@7f S"M

    /* Create a local array and load data */51Testing软件测试网;~A:Q;Y2Q%il&f
    dynamicData = mxMalloc(ELEMENTS * sizeof(double));51Testing软件测试网8u W4B? F.\5i-A
    for ( index = 0; index < ELEMENTS; index++ ) {
2Q,EQq;K}0        dynamicData[index] = data[index];
4H-n%b4|0V0    }
51Testing软件测试网9K'Z.kT(p7O

51Testing软件测试网 {&K7WL cZ

    /* Create a 2-by-2 mxArray; you will copy existing data into it */
N8RCxfx]+FS0    plhs[0] = mxCreateNumericMatrix(ROWS, COLUMNS, mxDOUBLE_CLASS, mxREAL);
0kc`8{9Q-d0    pointer = mxGetPr(plhs[0]);

Xonp Yr ey0

)`{!E*@k0    /* Copy data into the mxArray */51Testing软件测试网3z C7o8XxcwZ
    for ( index = 0; index < ELEMENTS; index++ ) {51Testing软件测试网6J6F(mL0z*|
        pointer[index] = dynamicData[index];51Testing软件测试网%?)U6oU.@)T
    }

2U9s8J;T7P^4_ H dW~x0 51Testing软件测试网*K-C*~S){tSh as

    /* You must call mxFree(dynamicData) on the local data.
W{A+C~0       This is safe because you copied the data into plhs[0] */
Gh}9`Sw0    mxFree(dynamicData);51Testing软件测试网X V!pG0p4Z&S Ju
   
r)q] ?$uo*{:jWd0    return;
(K%x9E)[8z'E;F0}
51Testing软件测试网.^TD1s'j&uuu QB


TAG:

 

评分:0

我来说两句

Open Toolbar