How do I get the number of members in a structure? - c

I want to count the number of members in a structure.
For example:
typedef struct
{
char MrChar;
int MrInt;
long MrLong;
} Bg_Typedef;
Bg_Typedef FooStr;
I create a function prototype that should return number of members in the structure
int NumberOfMem(Bg_Typedef *psStructure);
=> NumberOfMem(&FooStr) should return 3

It can be done with X_MACRO's.
Do something like this:
#define X_BG_MEMBERS \
X(char, MrChar) \
X(int, MrInt) \
X(long, MrLong)
typedef struct {
#define X(type, member) type member;
X_BG_MEMBERS
#undef X
} Bg_Typedef;
Bg_Typedef FooStr;
Define a function which will count the members. Can also just be a variable, but make the variable static const so that it is not overwritten
static int
bg_members_count() {
#define X(_, __) +1
static int COUNT = 0
X_BG_MEMBERS;
#undef X
return COUNT;
}
Now you can do something like this in main:
#include <stdio.h>
...
int main() {
printf("The number of members defined in Bg_Typedef is %d\n", bg_members_count());
}
You should get something like:
The number of members defined in Bg_Typedef is 3
You might also just want a constant, so you can do the following
#define X(_, __) +1
static const int COUNT = X_BG_MEMBERS;
#undef X
Alternative Pattern
In order to avoid having lots of #define X... followed by #undef X, it may be beneficial to do something like this instead:
#define X_BG_MEMBERS(X) \
X(char, MrChar) \
X(int, MrInt) \
X(long, MrLong)
#define BG_STRUCT_FIELD(type, field) type field;
#define BG_COUNT_MEMBER(_, __) +1
typedef struct {
X_BG_MEMBERS(BG_STRUCT_FIELD)
} Bg_Typedefarguably;
static int
bg_members_count() {
static int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);
return COUNT;
}
// OR constant
// static const int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);
It works the same as the above, but should be noticeably more readable. See ref.

There is no way to do this that is inbuilt into the C language AFAIK. If you want to do this you would need to remember the number of members or hard code the number as return value of your function. C can tell you the size in bytes of your structs but not the number of members they contain. Alternatively you could use a member function of your struct to return the hard coded number of members.

C only allows you to determine the number of bytes a structure requires (including padding bytes) using the sizeof operator. As long as the struct members all have the same type, you can use sizeof(struct foo)/sizeof(membertype) to compute the number of members. In the general case, with differently sized member types, this is impossible from within the C language (you could post process the source automatically and fill in the result, but that's ugly). C simply does not allow what is called Introspection in other languages (like e.g. perl).
But then, you (and the compiler) know the number of members at compile time. Why do you want to compute a known number at runtime? Maybe you can state the actual problem you are trying to solve and we can point to a solution not involving member counts...

This cannot be done in C.
If you really need this, you should try a more high level language which supports reflection. (Java, Python ).
http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29

Related

How to relate X-macro to array of function pointer

I applied X-macro mechanism to get enumeration-to-string relation.
#define CMD_TABLE \
X(cmd_A)\
X(cmd_B)\
////////////////////////////////////
typedef enum
{
EMPTY,
#define X(x) x,
CMD_TABLE
#undef X
}cmd_t;
////////////////////////////////////
const static struct
{
char* name;
cmd_t index;
} conversionMap[] = {
#define X(x) {#x, x},
CMD_TABLE
#undef X
};
Then, this function converts string to enum.
cmd_t str2enum(const char* str);
Finally, corresponding function is called by treating enum as the index of array.
(*func[index])();
This method has a big problem that it force programmer to remember enum-to-function mapping relationship.
In other words, in initialization stage, the order of following functions
void (*func[])(void) =
{
&cmd_A_function,
&cmd_B_function,
};
needs to be as same as that of CMD_TABLE.
Further, once CMD_TABLE grows, code is getting worse to maintain because
if a command is not going to support, people might delete wrong line in array of function pointer.
if I want to know what does cmd_Z do, I have to count up from 1 to 26.
list of CMD_TABLE and void (*func[])(void) will be far away from each other such that programmer needs to write code in two places in order to add one feature.
You have already used X-macro twice.
You can use it a third time.
Here is a proposal how to do that, using the ugly undef-using pattern you applied the first two times:
void (*func[])(void) =
{
#define X(x) &x##_function,
CMD_TABLE
#undef X
};

Looping through elements in a struct in C for extracting value and datatype of the individual element

I have a requirement where I have a big structure in C consisting of around more than 30 different elements of different data types:
typedef struct {
type1 element1;
type2 element2;
type3 element3;
type2 element4[10];
...
typeN elementN;
} my_messg_struct;
where this is basically a group of elements in a message sent over the serial protocol. This message has various elements of varying datatypes as captured in the above structure. Similarly, I have a lot of other messages as well. Now I have to write a generic function which is responsible for reading these message structs and loop through each of the elements reading the element's value and datatype and then transmitting over the serial port. I need to read the datatype first because the order of transmission of various datatypes is different in my case.
So, basically, I just wanted to know how to loop through elements of a struct in C in such a way that I can read the value and data type of each of the element present in a struct?
You could try to use X macros, but the resulting source code readability is questionable:
#include <stdio.h>
#define LIST_OF_VARIABLES \
XI(int, value1) \
XD(double, value2) \
XU(unsigned, value3)
#define XI(int, name) int name;
#define XD(double, name) double name;
#define XU(unsigned, name) unsigned name;
typedef struct A {
LIST_OF_VARIABLES
} A;
#undef XI
#undef XD
#undef XU
void print_variables(struct A a)
{
#define XI(type, name) printf("%s = %d\n", #type, a.name);
#define XD(type, name) printf("%s = %f\n", #type, a.name);
#define XU(type, name) printf("%s = %u\n", #type, a.name);
LIST_OF_VARIABLES
#undef XI
#undef XD
#undef XU
}
int main(void) {
A a = {
.value1 = 10,
.value2 = 0.5,
.value3 = 1,
};
print_variables(a);
return 0;
}
Now that you have a type string placed on every #type occurrence you could use some string comparison functions to determine what to based for each type.
C does not support traveling on struct members (something like reflection at C#,Java). You'll need to wrap each element with a struct stating its size, type and data. something like this:
typedef enum {
et_int,
et_long,
et_string,
et_array
}element_type_t;
struct element {
element_type_t type;
int element_length;
void *data;
};
BTW, there is a way to get reflection for struct, if one is using google protocol buffers. (see https://en.wikipedia.org/wiki/Protocol_Buffers) this way you can ask for each struct which members it has and of which type. however using this, involves using protocol buffer compiler and adding protocol buffer files to your project.

Use of macros in array definition in C

I am new to C and using it to program a Nordic nrf52 chip. I believe my problem is a general C one though rather than application.
I am setting up an array of structs using macros predefined in the chip SDK. Using those macros in the array initialisation works, but doing element by element does not.
So, the following works:
nrf_twi_mngr_transfer_t transfers_1[2] = { \
NRF_TWI_MNGR_WRITE(MSBARO5X_0_ADDR , &reg_addr[1], 1, NRF_TWI_MNGR_NO_STOP), \
NRF_TWI_MNGR_READ (MSBARO5X_0_ADDR , &p_buffer[0], sizeof(p_buffer), 0)
};
Where:
typedef struct {
uint8_t * p_data; ///< Pointer to the buffer holding the data.
uint8_t length; ///< Number of bytes to transfer.
uint8_t operation; ///< Device address combined with transfer direction.
uint8_t flags; ///< Transfer flags (see #ref NRF_TWI_MNGR_NO_STOP).
} nrf_twi_mngr_transfer_t;
NRF_TWI_WRITE and _READ are macros that use further macros, for example:
#define NRF_TWI_MNGR_WRITE(address, p_data, length, flags) \
NRF_TWI_MNGR_TRANSFER(NRF_TWI_MNGR_WRITE_OP(address), p_data, length, flags)
which uses
#define NRF_TWI_MNGR_WRITE_OP(address) (((address) << 1) | 0)
and
#define NRF_TWI_MNGR_TRANSFER(_operation, _p_data, _length, _flags) \
{ \
.p_data = (uint8_t *)(_p_data), \
.length = _length, \
.operation = _operation, \
.flags = _flags \
}
What I want to do is change individual items in this array, for example:
transfers_1[0] = NRF_TWI_MNGR_WRITE(MSBARO5X_0_ADDR , &reg_addr[1], 1, NRF_TWI_MNGR_NO_STOP);
However when I do that, I get the error "expected an expression".
MSBARO5X_0_ADDR is also defined in a define statement:
#define MSBARO5X_0_ADDR 0x76
If I replace this in any of the above code with a variable, I get the same "expected an expression" error. I suspect the two problems I have are due to the same lack of understanding on my part. SO forgive me for combining the two in a single post.
So the questions are:
-Why am I getting this error?
-Is it possible to change individual items in my array, and if so how?
-Is it possible to use a variable in place of the MSBARO5X_ADDR, and if so how?
Many thanks!
Ultimately, the macro expands into a brace enclosed initializer. Such a thing is not an expression, so it cannot be used as the right hand side of plain assignment (assignment and initialization are different things). It will work as part of a larger initializer, but not the way you try to use it unmodified.
But all is not lost. The syntax of the initializer implies c99 support. So we can use a trick. Structure objects can be assigned to eachother. So we need only obtain an object from somewhere. We can use a compound literal in order to create said object:
transfers_1[0] = (nrf_twi_mngr_transfer_t)NRF_TWI_MNGR_WRITE(/*Your arguments*/);
If you define the value of a structure the moment you declare it, the compiler will infer the type of the structure from the declaration. So this here will compile:
struct coordinates {
int x;
int y;
};
struct coordinates origin = { 10, 20 }; // This is OK
But if you assign a value to a previously declared variable, the compiler cannot infer its type. This code won't compile:
struct coordinates origin;
origin = { 10, 20 }; // ERROR! The type of the rvalue is unknown!
The type is unknown, because two structures are not equivalent in C just because they have the same members. E.g. this is legal in C:
struct coordinates {
int x;
int y;
};
struct dayOfYear {
int day;
int month;
};
Now what would { 5, 8 } be? The coordinates (5/8) or the 5th of August? It could be both. All that he compiler knows is that it is a struct of type { int, int }. Yet this does not define a type in C. The following is possible in some languages but it's not possible in C:
struct dayOfYear date = { 2, 3 };
struct coordinates cords = date; // ERROR!
Despite the fact that both structures are of type { int, int }, for the compiler struct dayOfYear and struct coordinates are two completely distinct and unrelated data types.
If you want to declare a hardcoded struct value, you need to tell the compiler what kind of struct that is:
struct coordinates origin;
origin = (struct coordinates){ 10, 20 }; // This is OK
Your NRF_TWI_MNGR_TRANSFER defines a hardcoded struct but only when you use that in a definition the compiler knows the type. If you try to use it as an assignment, you need to cast to the correct type.
transfers_1[0] = (nrf_twi_mngr_transfer_t)NRF_TWI_MNGR_WRITE(MSBARO5X_0_ADDR , &reg_addr[1], 1, NRF_TWI_MNGR_NO_STOP);
Which is not really a cast, even though it has the same syntax. In fact this is just telling the compiler how to interpret the following data.

Comparing Types Of Names In C

I'm trying to write a macro in C (alas, not C++) in a way to trap certain errors, in particular if I pass a name of the wrong type.
For example, with
typedef int APLNELM;
typedef int APLRANK;
#define IsScalar(a) ((a) == 0)
APLNELM AplNelm = 0;
APLRANK AplRank = 0;
Calling IsScalar (AplRank) is correct because Scalar is a Rank concept, but IsScalar (AplNelm) is wrong because Scalar is not a # elements concept.
Can some clever person find a way to write the IsScalar macro such that it checks the type of the name passed to it to ensure that it is of type APLRANK? Feel free to rewrite the original example in any equivalent way if that provides a solution.
If these are the only two types that will ever be passed into the isScalar macro, then you could do something like this:
#include <stdio.h>
struct APLNELM {
int nelm;
char a[1];
};
struct APLRANK {
int rank;
char a[2];
};
#define isScalar(b) (sizeof b.a == 2)
int main(void) {
// your code goes here
struct APLNELM temp1;
struct APLRANK temp2;
printf("%d\n", isScalar(temp1));
printf("%d\n", isScalar(temp2));
return 0;
}
The output of this code is
0
1
This will work, but I highly suggest you don't use it as it wouldn't be super maintainable:
typedef int APLNELM;
typedef int APLRANK;
typedef unsigned int TYPETRAITS;
#define TRAIT_SCALAR 0x1
#define TYPETRAITS_APLNELM TRAIT_SCALAR /*whatever else you want, up to 32 traits*/
#define TYPETRAITS_APLRANK 0/*whatever else you want, up to 32 traits*/
#define GET_TYPE_TRAITS(X) TYPETRAITS_##X
#define IS_SCALAR(X) (X & TRAIT_SCALAR)
#define IS_TYPE_SCALAR(X) IS_SCALAR(GET_TYPE_TRAITS(X))
int main()
{
const int aplnelm_traints = GET_TYPE_TRAITS(APLNELM);
const int aplrang_traints = GET_TYPE_TRAITS(APLRANK);
const bool is_aplnelm_scalar = IS_TYPE_SCALAR(APLNELM);
const bool is_aplrang_scalar = IS_TYPE_SCALAR(APLNELM);
}
I gived up with following code (requires GNU extensions: typeof and Statement Exprs):
#include <stdio.h>
typedef int APLNELM;
typedef int APLRANK;
#define IsScalar(a) \
({ \
/* Override typedefs in block scope */ \
typedef char APLNELM; \
typedef int APLRANK; \
/* Create variable with typeof(a) type; \
* then compare it by sizeof with APLNELM */ \
typeof(a) b; sizeof b == sizeof(APLNELM); \
})
int main(void)
{
APLNELM a = 5;
APLRANK b = 5;
printf("IsScalar: %d\n", IsScalar(a) ? 1 : 0);
printf("IsScalar: %d\n", IsScalar(b) ? 1 : 0);
return 0;
}
The thing is that typeof(a) is actually not replaced by APLNELM or APLRANK. C is not dynamic language, I agree that struct concept would be better suited for such differentiation.
If you want to define two integer types that are different, the straight typedef approach fails, because typedef creates synonyms for the same type, never creates new types.
There is a manner to create different integer types, but even in this case, there is no way to "detect" them through their values.
For example, observe this code:
enum myint1_e {min1 = -32767, max1 = 32767};
enum myint2_e {min2 = -32767, max2 = 32767};
typedef enum myint1_e integer1_t;
typedef enum myint2_e integer2_t;
integer1_t x1 = 0;
integer2_t x2 = 0;
Now, the two types enum myint1_t and enum myint2_t are different integer types.
See C11: 6.7.2.3.(par.5):
Two declarations of [...] enumerated types which are in different scopes or use different tags declare distinct types.
So, their typedef-ed versions are, too, different.
Thus, the variables x1 and x2 have different types.
The integer value 0 can be assigned to both variables.
Now, if you want to check that the type of a variable is the one that you want, you can try doing that:
#define VERIFY_INT1TYPE(a) ((integer1_t*)(0) == (&a))
But this method only offers a Warning message, and not the "comparisson with value false" that you expected.
Explanation: Although the integer types are, in some way, interchangeable in assignment operations, on the other hand their "pointer to" versions are always different types. Thus, a sentence like x1 == x2 has not any problem at all, but the comparisson of a value of two different pointer types will raise a warning message.
Remark: The expression (integer1_t*)(0) is the NULL pointer cast to type integer1_t*.
Example:
VERIFY_INT1TYPE(x2);
This example raise a warning message when I compiled with GCC.
One possibility is to wrap the integer in a one-field struct, to enforce strong typing. To avoid the final production code being suboptimal, compile twice with different macro definitions; once with structs to detect errors, once without structs for optimal code.
#ifdef STRONG_TYPING
#define TYPE(basetype, field) struct { basetype field; }
#define INITIALIZER(value) {(value)}
#define AS_BASETYPE(field, value) ((value).field)
#else
#define TYPE(basetype, field) basetype
#define INITIALIZER(value) (value)
#define AS_BASETYPE(field, value) (value)
#endif
typedef TYPE(int, alpnelm) APLNELM;
typedef TYPE(int, alprank) APLRANK;
#define IsScalar(a) (AS_BASETYPE(aplrank, a) == 0)
With STRONG_TYPING defined, IsScalar(SomeAplNelm) will give a compiler error. Without STRONG_TYPING, the overhead of structs will be completely gone. Naturally, all modules must to be compiled with the same definition before linking, or your executable is likely to crash.
In your program code, you will have to apply some discipline when it comes to using the macros. Declaration example:
APLNELM MyAplNelm1;
APLNELM MyAplNelm2 = INITIALIZER(0);
Assignment:
AS_BASETYPE(aplnelm, MyAplNelm1) = 0;
AS_BASETYPE(aplnelm, MyAplNelm2) = AS_BASETYPE(aplnelm, MyAplNelm1);
It is still allowed to exchange values between different 'strong' types; as long as you specify the correct type (name of the field in the struct) for each individual value.
AS_BASETYPE(aplnelm, MyAplNelm2) = AS_BASETYPE(aplrank, MyAplRank);
Please note you always need AS_BASETYPE to access a variable of one of the 'strong' types. This will make the code more verbose (please feel free to choose a shorter name for the macro), but there's nothing wrong with that. It's just a notion of metadata you are adding; it should actually improve maintainability.

Is there any way to loop through a struct with elements of different types in C?

my struct is some like this
typedef struct {
type1 thing;
type2 thing2;
...
typeN thingN;
} my_struct
how to enumerate struct childrens in a loop such as while, or for?
I'm not sure what you want to achieve, but you can use X-Macros and have the preprocessor doing the iteration over all the fields of a structure:
//--- first describe the structure, the fields, their types and how to print them
#define X_FIELDS \
X(int, field1, "%d") \
X(int, field2, "%d") \
X(char, field3, "%c") \
X(char *, field4, "%s")
//--- define the structure, the X macro will be expanded once per field
typedef struct {
#define X(type, name, format) type name;
X_FIELDS
#undef X
} mystruct;
void iterate(mystruct *aStruct)
{
//--- "iterate" over all the fields of the structure
#define X(type, name, format) \
printf("mystruct.%s is "format"\n", #name, aStruct->name);
X_FIELDS
#undef X
}
//--- demonstrate
int main(int ac, char**av)
{
mystruct a = { 0, 1, 'a', "hello"};
iterate(&a);
return 0;
}
This will print :
mystruct.field1 is 0
mystruct.field2 is 1
mystruct.field3 is a
mystruct.field4 is hello
You can also add the name of the function to be invoked in the X_FIELDS...
There is no safe way to enumerate a struct's members, unless the exact contents of the struct is known, and even in that case you have to be careful of things like struct alignment/padding.
Depending on your problem, it might be safer to have an array of your struct.
Since you plan to handle them in a loop, I assume the different types can at least be treated alike, or have similar sizes.
If this is the case, your choice will depend on the size of the elements. If they're all the same, you can retrieve a pointer to the structure, cast it to one of your types, and increment it until you 'used up' the whole structure.
PS: Indeed, not a very safe practice. This a situation handled much better with an OO approach, taking advantage of polymorphism. Otherwise, there's no guarantees about alignment as previously mentioned.
There's no way to iterate through struct members in C language, regardless of whether the have the same size/type or different sizes/types.
For the reference, you can loop through struct elements using pointer arithmetic, if they are the same type:
typedef struct numbers{
int a;
int b;
int c;
} numbers;
numbers nums;
nums.a = 42;
nums.b = 99;
nums.c = 23;
int count = sizeof(nums) / sizeof(int); // 3
for(int i=0; i < count; i++){
printf("%d ", *(&nums.a + i) ); // start on the first field's address
}

Resources