03-04-2022 09:23 AM
I everyone,
I want to write a piece of very generic code to automatically declare a variable according to the control Attribute ATTR DATA TYPE in order to read any type of Control value.
The pseudo code looks as follow
For All Control in a Panel
If It's a numeric Control type
| get control data type (GetCtrlAttribute(panel, Ctrl, ATTR_DATA_TYPE, ...)
| declare variable according to the control data type (???)
| read control value and put it in the variable (GetCtrlVal)
Any idea?
Thank you.
03-07-2022 02:50 AM
C doesn't have dynamic typing.
There are two ways to go around this usually: with a void* or a union.
// Direct check
int dt, MyInt;
double MyDouble;
GetCtrlAttribute (, , ATTR_DATA_TYPE, &dt);
switch (dt) {
case VAL_INTEGER:GetCtrlVal(,,&MyInt); break;
case VAL_DOUBLE: GetCtrlVal(,,&MyDouble); break;
}
// Using void*
void* MyData;
// ... get MyData somehow, for instance with fread
switch (dt) {
case VAL_INTEGER:MyInt=*(int*)MyData; break;
case VAL_DOUBLE: MyDouble=*(double*)MyData; break;
}
// Using union
typedef struct sSomeType {
int dt;
union {
int MyInt;
double MyDouble;
}
} tSomeType;
tSomeType SomeType;
switch (SomeType.dt) {
case VAL_INTEGER:AnInt=SomeType.MyInt; break;
case VAL_DOUBLE: ADouble=SomeType.MyDouble; break;
}
03-09-2022 02:04 AM
Thank for answering and for these elegant solutions.
Best regards
03-09-2022 03:01 AM
There might be a more elegant solution using C11 generics, but I rarely use them and I don't even know if they are supported by the current versions of the CVI compiler.