Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differentiating struct based on type

Tags:

c

struct

I have two different structures with a type field define(Please see below).

struct A {
int type;
char type_a[8];
char random[8];
};


struct B {
int type;
char type_b[16];
char random[16];
};

Now I want to differentiate this two structures based on type So for example

if (type == A)
struct A *a = (struct A *)buff;
if (type == B)
struct B *b = (struct B *)buff;

I don't know what type of structure is passed to me in buff before hand. So how do I extract type from the buff. The type field is guranteed to be the first field in both the structures.

like image 528
kunal patel Avatar asked Dec 07 '25 19:12

kunal patel


1 Answers

You can do this type of thing with an OOP design pattern in C.

The idea here is that a Base structure has a type member. Structures A and B "extend" Base. Since the Base structure is the first member of both A and B, either can be cast to Base and used as such.

That'll give you a safe way to cast in between Base and A or B while giving compile-time type safety when you just need to use an instance of Base.

typedef struct Base {
    int type;
} Base;

typedef struct A {
    Base base;
} A;

typedef struct B {
    Base base;
} B;

int ATYPE = 1;
int BTYPE = 2;

int getType(Base *base) {
    return base->type;
}

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    B b;
    B *bptr;
    Base *base;
    int baseType;

    a.base.type = ATYPE;
    b.base.type = BTYPE;

    base = (Base*)&b;

    baseType = getType(base);

    // something like this is reasonable,
    // since you know that base is an
    // instance of B.
    if (baseType == BTYPE) {
        bptr = (B*)base;
    }

    if (baseType != BTYPE) return -1;
    return 0;
}
like image 136
ken Avatar answered Dec 09 '25 17:12

ken