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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值