jweinst1
7/3/2017 - 10:03 PM

example macro for handles in c

example macro for handles in c

#include "stdio.h"
#include "stdlib.h"

#define XenObject_HANDLE unsigned char type;

typedef struct
{
    XenObject_HANDLE
} XenObject;

#ifndef XenObject_TYPE
#define XenObject_TYPE(xo) xo->type
#endif

#define XenObject_SETTYPE(xo, t) xo->type = t 

typedef struct
{
  XenObject_HANDLE
  int num;
} XenInt;

#define XenObject_CAST_INT(xo) (XenInt*)xo
#define XenInt_CAST_OBJ(xoi) (XenObject*)xoi
#define XenInt_GET_INT(xoi) xoi->num
#define XenInt_SET_INT(xoi, i) xoi->num = i

int main(void) {
  printf("Hello World\n");
  XenObject g = {1};
  XenObject *h = &g;
  XenObject_SETTYPE(h, 6);
  XenInt* p = malloc(sizeof(XenInt));
  XenInt_SET_INT(p, 5);
  printf("The type is %d\n", XenObject_TYPE(h));
  printf("The value of the int is %d\n", XenInt_GET_INT(p));
  h = XenInt_CAST_OBJ(p);
  XenObject_SETTYPE(h, 2);
  printf("The type is %d\n", XenObject_TYPE(h));
  return 0;
}