0
votes

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?

1
Is it yourself that provides the implementation of GetData or is that a library of which you cannot access or change the source code?Vincenzo Pii
Library provides me the implementation.RKum
You pass a pointer to some memory which is large enough to hold the larger of the two structs. Casting and further processing is then done according to the return value of GetData(). In case the smaller struct is constructed some memory is wasted, but that's unavoidable.Peter - Reinstate Monica
Thanks Peter for the explanation and James for the implementation.RKum

1 Answers

5
votes

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!