M
Mark A. Odell
Is there a way to obtain the size of a struct element based only upon its
offset within the struct? I seem unable to figure out a way to do this
(short of comparing every element's offset with <offset>). What I would
like to do is create an API something like this:
#include <stddef.h>
struct MemMap
{
unsigned char apple; // 8 bits on my platform
unsigned char butter;
unsigned short pear; // 16 bits on my platform
unsigned long peach; // 32 bits on my platform
};
static struct MemMap memMap;
/* <offset> is the offset of the MemMap struct element
** that this function is to write with the appropriately
** sized value pointed to by <pVal>.
*/
int writeMemMapReg(size_t offset, void *pVal)
{
int failures = 0;
size_t size = /* sizeof element at <offset> */;
unsigned char *p8Bits;
unsigned short *p16Bits;
unsigned long *p32Bits;
switch (size)
{
case 1:
p8Bits = (unsigned char *) pVal;
/* somehow write *p8Bits to memMap struct at
** <offset>.
*/
break;
case 2:
p16Bits = (unsigned short *) pVal;
/* somehow write *p16Bits to memMap struct at
** <offset>.
*/
break;
case 4:
p32Bits = (unsigned long *) pVal;
/* somehow write *p32Bits to memMap struct at
** <offset>.
*/
break;
default:
/* Error */
failures = !0;
break;
}
return failures;
}
Any help much appreciated.
offset within the struct? I seem unable to figure out a way to do this
(short of comparing every element's offset with <offset>). What I would
like to do is create an API something like this:
#include <stddef.h>
struct MemMap
{
unsigned char apple; // 8 bits on my platform
unsigned char butter;
unsigned short pear; // 16 bits on my platform
unsigned long peach; // 32 bits on my platform
};
static struct MemMap memMap;
/* <offset> is the offset of the MemMap struct element
** that this function is to write with the appropriately
** sized value pointed to by <pVal>.
*/
int writeMemMapReg(size_t offset, void *pVal)
{
int failures = 0;
size_t size = /* sizeof element at <offset> */;
unsigned char *p8Bits;
unsigned short *p16Bits;
unsigned long *p32Bits;
switch (size)
{
case 1:
p8Bits = (unsigned char *) pVal;
/* somehow write *p8Bits to memMap struct at
** <offset>.
*/
break;
case 2:
p16Bits = (unsigned short *) pVal;
/* somehow write *p16Bits to memMap struct at
** <offset>.
*/
break;
case 4:
p32Bits = (unsigned long *) pVal;
/* somehow write *p32Bits to memMap struct at
** <offset>.
*/
break;
default:
/* Error */
failures = !0;
break;
}
return failures;
}
Any help much appreciated.