c语言借助GNU创建对象和嵌套union使用

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* 
 * 枚举体占用内存
 * 枚举有符号,根据数值分配内存。[1~4]
 * 但是和编译器相关联,目前我看到的都是4byte
 */
typedef enum {
  MONKEY_TYPE = 0,
  DOG_TYPE = 1,
}object_type_t;
typedef struct{
  char name[10];
  unsigned char age;
}__attribute__((packed)) monkey;
typedef struct{
  char name[10];
  unsigned char age;
} __attribute__((packed)) dog;
/* 结构体嵌套共用体,用一个标记字段来区分union中存储的是什么,节约内存,非常常用这种方法 */
typedef struct 
{
  object_type_t type;
  /* 取消字节对齐 */
  union {
   monkey m;
   dog d;
  } __attribute__((packed));
}__attribute__((packed)) person;

/* c 语言创建对象方法 */
#define VLIB_INIT_PERSON(x) \
  person* x;                \
  static void __attribute__((constructor)) init_person();\
  static void init_person()\
  {\
    printf("init a person\n");\
    x = (person*)malloc(sizeof(person));\
  }\
  static void __attribute__((destructor)) free_person();\
  static void free_person()\
  {\
    printf("free has been finished!\n");\
    free(x);\
  }\
  static void print(const person *p);\
  static void print(const person *p) \
  {\
    switch (p->type) {\
      case MONKEY_TYPE:\
        printf("{type:monkey; name:%s; age:%u;}\n", p->m.name, p->m.age);\
        break;\
      case DOG_TYPE:\
        printf("{type:dog; name:%s; age:%u;}\n", p->d.name, p->d.age);\
        break;\
      default: \
        break;\
    }\
  }\
/* call macro */
VLIB_INIT_PERSON(p)
int
main (int argc, char *argv[])
{
  p->type = MONKEY_TYPE;
  strcpy(p->m.name, "孙悟空");
  p->m.age = 12;

  print(p);

  p->type = DOG_TYPE;
  memcpy(p->d.name, "汪汪", sizeof(p->d.name));
  p->m.age = 12;

  print(p);

  return 0;
}
posted @ 2022-11-05 15:02  nanfengnan  阅读(44)  评论(0编辑  收藏  举报