Friday, January 10, 2014

m4 macro which realize indexer in C

I introduce m4 macro which realize indexer like C# in C.
There is still room for improvement on this program,however I think I want to introduce as a temporary program.
define(`defObject',`
        setIndexer($2)
        $1 $2=NULL;
        $2=$1Init(shift($@));
');
define(`setIndexer',`define(`$1',
                `if'`else('
                        `$'`#'`,2,'
                        ``$1''`->a['`$'`1'`*'`$'`2'`],
                        ``$1'''
                `)'
        )
');

#include <stdlib.h>

typedef struct{
        int *a;
} testObj;
testObj *testObjInit(void *a,int n){
        struct testObj *result=malloc(sizeof(struct testObj));
        result->a=malloc(sizeof(int)*n);
 return result;
}
int main(void){
        defObject(testObj,objs,1024);    //(1)
        objs(1,3)+=1;//realize access like indexer here.
 objs->a[2]=2;//can do normal access.
}
Position (1),First argument is type name and second argument is variable name defined.
Arguments after third  are data that is given to testObjInit.
[type name]Init can is called in defObject.(Use testObjInit in this case )
setIndexer macro which is called in defObject is a function realizing indexer.

No comments:

Post a Comment