C struct containing union to LiteC

Posted By: 3Dski

C struct containing union to LiteC - 03/27/07 04:33

Is there any way to port a structure definition from C that contains a union to LiteC? The structure containing the union needs to be consistent with C, because it is passed to an existing DLL function.
Posted By: jcl

Re: C struct containing union to LiteC - 03/27/07 09:50

Unions are not supported by lite-C. Union members of the same type can be substituted by a #define; union members of different type can be treated as different members of the struct. Example:

Code:
typedef struct S_UNION { 
int data1;
union { int data2; float data3; };
union { int data4; int data5; };
} S_UNION; // C/C++

typedef struct S_UNION {
int data1;
int data2;
float data3;
int data4;
} S_UNION; // lite-C
#define data5 data4;



If the struct size must not change, or if the program requires different variable types to occupy the same place in the struct, a special conversion function can be used to convert the type of a variable without converting the content:

Code:
typedef struct S_UNION { 
int data1;
union { int data2; float data3; };
} S_UNION; // C/C++
...
S_UNION s_union;
s_union.data3 = 3.14;

typedef struct S_UNION {
int data1;
int data2;
} S_UNION; // lite-C
...
int union_int_float(float x) { return *((int*)&x); }
...
S_UNION s_union;
s_union.data2 = union_int_float(3.14);


Posted By: 3Dski

Re: C struct containing union to LiteC - 03/28/07 04:54

I realized that LiteC didn't support unions, and also remembered enough to know that unions may have special properties that would keep me from simply replacing them with a like struct.

In your second example, are you actually creating a rogue "data3" member?! Confusing, because the LiteC S_UNION hasn't been defined yet, and when you do define it, it doesn't contain "data3". I wouldn't have thought that "s_union.data3 = 3.14" would be allowed at that place in the code. I also would have never thought that "s_union.data3" would serve as phantom member. Am I understanding this correctly?... and thanks much for the info : )
© 2024 lite-C Forums