Posts tagged ‘Languages’

01/17/2011

Passing Argument in Mex function without modifying C code

#include “mex.h”
#include “matrix.h”

void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
int argc = 0;
char **argv;
int i, result;

argc = nrhs;
argv = (char **) mxCalloc( argc, sizeof(char *) );

for( i=0; i
{
if( !mxIsChar( prhs[i] ) ){
mexErrMsgTxt(“Input must be of type char.”);
return;
}
argv[i] = mxArrayToString( prhs[i] );
}

result = myfunction( argc, argv );

for( i=argc-1; i>=0; i– )
mxFree( argv[i] );
mxFree( argv );

if( result )
mexErrMsgTxt(“main function causes an error”);
}

This function pass the arguments string to the main function.If you have a large piece of C code, it might be cumbersome process to change code to fit mex style. But this code will just read arguments list and pass it to the main function.

For example, if the c function call is

myfunciton -f1 mpeg4.flt -mc mc_filename

then, the mex function call is

myfunction(‘myfunction’,'-f1′,’mpeg4.flt’,'-mc’,'mc_filename’)

Note that first argument for mex function is function name because c function keeps first argument (argv[0]) funciton name.

<How to use>

1. Put this code in front of the C code.

2. Change the name ‘main’ to different name like ‘myfunction.’

3. Compile mex file by typing ‘mex myfunction.c’ in Matlab command window.

 

 

 

Follow

Get every new post delivered to your Inbox.