c_cpp 从c中的未被发现的指针中获取值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 从c中的未被发现的指针中获取值相关的知识,希望对你有一定的参考价值。

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

//generic macros for accessing casted pointer types

//macro for Base
#define BASE_HANDLE int type; \
  struct Base* next; \
  struct Base* prev;

struct Base {
  BASE_HANDLE
};

typedef struct Base Base;

//object that represents integer.
typedef struct {
  BASE_HANDLE
  long value;
} IntObj;

//constructs new int casted back to base
Base* IntObj_new(long value)
{
  IntObj* iob = malloc(sizeof(IntObj));
  iob->type = 1;
  iob->value = value;
  return (Base*)iob;
}

#define IntObj_GET_INT(bs) ((IntObj*)bs)->value

int main(void) {
  Base* foo = IntObj_new(7);
  
  printf("The number is %d\n", IntObj_GET_INT(foo));
  return 0;
}

以上是关于c_cpp 从c中的未被发现的指针中获取值的主要内容,如果未能解决你的问题,请参考以下文章