Archive for ‘C++&C’

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.

 

 

 

01/13/2011

Variable Number of Argument

I am looking at the QCC package, and one function has

void QccStringSprintf(QccString qccstring, const char *format, …)

I didn’t know what the right most ‘…’ characters. After searching some info about it, I found the function allows variable number of variables. So I put one good example directly from

http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
main(){
        f();
        exit(EXIT SUCCESS);
}
int maxof(int n args, ...){
        register int i;
        int max, a;
        va_list ap;
        va_start(ap, n args);
        max = va_arg(ap, int);
        for(i = 2; i <= n_args; i++) {
                if((a = va_arg(ap, int)) > max)
                        max = a;
        }
        va_end(ap);
        return max;
}
void f(void) {
        int i = 5;
        int j[256];
        j[42] = 24;
        printf("%dn",maxof(3, i, j[42], 0));
}

Read more at publications.gbdirect.co.uk

 

01/05/2011

Becoming a spiritual house. 1 Peter John Piper

나는 하나님의 영광을 위해 살며 내가 하는 모든 일을 영적 예배로 드리고 그렇게 하기 위해 매 순간 성령님을 의지하고 또 우리의 기초반석이 되시는 하나님께 나아간다.
Sungkwang

Follow

Get every new post delivered to your Inbox.