core/matlab/examples/refbook/revord.c

00001 /* $Revision: 1.1 $ */
00002 /*=================================================================
00003  * revord.c 
00004  * example for illustrating how to copy the string data from MATLAB
00005  * to a C-style string and back again
00006  *
00007  * takes a row vector string and returns a string in reverse order.
00008  *
00009  * This is a MEX-file for MATLAB.
00010  * Copyright 1984-2006 The MathWorks, Inc.
00011  *=============================================================*/
00012 #include "mex.h"
00013 
00014 void revord(char *input_buf, mwSize buflen, char *output_buf)
00015 {
00016   mwSize i;
00017 
00018   if (buflen == 0) return;
00019 
00020   /* reverse the order of the input string */
00021   for(i=0;i<buflen-1;i++) 
00022     *(output_buf+i) = *(input_buf+buflen-i-2);
00023 }
00024 
00025 void mexFunction( int nlhs, mxArray *plhs[],
00026                   int nrhs, const mxArray *prhs[])
00027 {
00028     char *input_buf, *output_buf;
00029     mwSize buflen;
00030     
00031     /* check for proper number of arguments */
00032     if(nrhs!=1) 
00033       mexErrMsgTxt("One input required.");
00034     else if(nlhs > 1) 
00035       mexErrMsgTxt("Too many output arguments.");
00036 
00037     /* input must be a string */
00038     if ( mxIsChar(prhs[0]) != 1)
00039       mexErrMsgTxt("Input must be a string.");
00040 
00041     /* input must be a row vector */
00042     if (mxGetM(prhs[0])!=1)
00043       mexErrMsgTxt("Input must be a row vector.");
00044     
00045     /* get the length of the input string */
00046     buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
00047 
00048     /* allocate memory for output string */
00049     output_buf=mxCalloc(buflen, sizeof(char));
00050 
00051     /* copy the string data from prhs[0] into a C string input_ buf.    */
00052     input_buf = mxArrayToString(prhs[0]);
00053     
00054     if(input_buf == NULL) 
00055       mexErrMsgTxt("Could not convert input to string.");
00056     
00057     /* call the C subroutine */
00058     revord(input_buf, buflen, output_buf);
00059 
00060     /* set C-style string output_buf to MATLAB mexFunction output*/
00061     plhs[0] = mxCreateString(output_buf);
00062     mxFree(input_buf);
00063     return;
00064 }
00065 

GridLAB-DTM Version 1.0
An open-source project initiated by the US Department of Energy