RKum
RKum

Reputation: 831

C Functions taking void * function parameter

Earlier I had one structure C

typedef struct c
{
    int cc;
}CS;

I used to call a library function say int GetData(CS *x) which was returning me the above structure C with data.

GetData(CS *x)

Function call used to be like:

CS CSobj;
GetData(&CSObj);

Now there are two structures say C and D

typedef struct c
{
    int cc;
}CS;
CS CSobj;

typedef struct d
{
    int dc;
    int dd;
}DS;
DS DSobj;

Function GetData() has been modified to GetData(void* x). I have to call the library function say int GetData(void* x) which will be returning me one of the above structures through that void* paramter. The return type of the function tells which structure is returned.

Problem is while calling the function GetData() how and what parameter to pass since I am unaware of which struct the function will return. Any way out of this problem?

Upvotes: 0

Views: 230

Answers (1)

James Anderson
James Anderson

Reputation: 27488

You could use a union

 // define union of two structs
    union DorC {
       DS DSobj;
       CS CSobj;
    } CorD;

 // call using union
 rc = GetData(&CorD);
 if (rc == Ctype) {
     // use CorD.CSobj;
 } else {
     // use CorD.DSobj;
 }

Warning untested un syntax checked code!

Upvotes: 5

Related Questions