A generic datatype for C

    var a ;
    a = data(10);
    a = data("hello");
    a = data("hello","world");

The above doesnt look like a C code but will be fun to achieve .

The first problem in this case to recognize the number of inputs given to our “data” function , uhmmmmm .. but how ?? not possible in C right ? Lets see the following piece of code .

    #define NUM_ARGS( ...) NUM_ARGS_ ( __VA_ARGS__ , MAX_N())
    #define NUM_ARGS_(...) NUM_ARGS_N(__VA_ARGS__)
    #define NUM_ARGS_N(_1,_2,_3,[..],_61,_62,_63,N,...) N
    #define MAX_N() 63,62,61,60,[..],9,8,7,6,5,4,3,2,1,0

Let there be input !!


NUM_ARGS(A,B,C)

NUM_ARGS_(A,B,C,63,62,61,[…],3,2,1,0)

The above input need to fill _1,_2,_3…..,_61,_62,_63,N …

A is replaced at _1

B is replaced at _2

C is replaced at _3

63 is replaced at _4

62 is replaced at _5

[……]

4 is replaced at _63

Thus N will become 3 … Bingo !!

Now we need to manage our “data” . An easy way out will be to find out somehow the “type” of input we are getting and transfer the handle to seperate functions .

    #define data(x , args ...) \
    ({ \
    var num; \
    if (__builtin_types_compatible_p (typeof (x), int)) \
    num = _intCB(NUM_ARGS(args),x, ##args); \
    else \
    num = _chrCB (NUM_ARGS(args),x,##args); \
    num; \
    })

This will easily take care of the different input types and call _intCB function in case it gets integer input and will call _chrCB in other cases .
For defining our little variable “var” we can use following structure .

    typedef struct {
            void *data;
            int data_type;
     } var;

So now our receipe is complete . You can see complete code at

https://github.com/nautical/CBullet/blob/master/pie.h

 
19
Kudos
 
19
Kudos

Now read this

Experiment with Embedded Solr in java and C

Solr is poster boy in search market . Generally it is used by running as HTTP server and making queries . I was more interested in running it in embedded manner and getting results via JNI . Following you will find the code for doing... Continue →