C语言指针转换为 intptr_t 类型

  1. intptr_t类型
    数据类型特别是int相关的类型在不同位数机器的平台下长度不同。C99标准并不规定具体数据类型的长度大小。

C语言指针转换为 intptr_t 类型_第1张图片


为了保证平台的通用性,程序中尽量不要使用long类型。可以使用固定大小的数据类型宏定义,这些宏定义需要引用stdint.h头文件。

/* There is some amount of overlap with  as known by inet code */
#ifndef __int8_t_defined
# define __int8_t_defined
typedef signed char         int8_t;
typedef short int          int16_t;
typedef int               int32_t;
# if __WORDSIZE == 64
typedef long int          int64_t;
# else
__extension__
typedef long long int        int64_t;
# endif
#endif

/* Unsigned.  */
typedef unsigned char         uint8_t;
typedef unsigned short int    uint16_t;
#ifndef __uint32_t_defined
typedef unsigned int          uint32_t;
# define __uint32_t_defined
#endif
#if __WORDSIZE == 64
typedef unsigned long int       uint64_t;
#else
__extension__
typedef unsigned long long int    uint64_t;
#endif

关于intptr_t的类型定义如下:

/* Types for `void *' pointers.  */
#if __WORDSIZE == 64
# ifndef __intptr_t_defined
typedef long int               intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned long int    uintptr_t;
#else
# ifndef __intptr_t_defined
typedef int                    intptr_t;
#  define __intptr_t_defined
# endif
typedef unsigned int        uintptr_t;
#endif
  • 从定义可以看出,intptr_t在不同的平台是不一样的,始终与地址位数相同,因此用来存放地址,即地址。

3. 指针与intptr_t

  • C语言指针用来保存变量或常量的地址,地址由处理器的位数决定。在windows程序中,经常用到句柄,其实就是一个地址,具备通用性,对底层进行了封装。先对这个理解不深刻,什么时候需要将指针转换为intptr_t类型。

4. 测试程序:

#include 
#include 
#include 
#include 
#include 
#include 

#define ID_STR_LEN   12
#define NAME_STR_LEN 10

typedef struct student
{
    char id[ID_STR_LEN];
    char name[NAME_STR_LEN];
    uint8_t age;
}student;

student * create_student()
{
    student *stu = (student *)malloc(sizeof(student));
    if (stu == NULL)
    return NULL;
    memset(stu, 0, sizeof(student));
    return stu;
}

void *free_student(student *stu)
{
    if (stu)
    free(stu);
}

static void init_student(student * stu)
{
    assert(stu);
    const char *id = "2013112210";
    const char *name = "Anker";
    uint8_t age = 21;
    memcpy(stu->id, id, strlen(id));
    memcpy(stu->name, name, strlen(name));
    stu->age = age;
}

static int handle_student(intptr_t handle)
{
    if (handle == 0)
    {
    return -1;
    }
    student *stu = (student*)handle;
    printf("id: %s\n", stu->id);
    printf("name: %s\n", stu->name);
    printf("age: %u\n", stu->age);
    return 0;
}

int main()
{
    student *stu;
    stu = create_student();
    init_student(stu);
    //将指针转换为intptr_t类型
    intptr_t handle = (intptr_t)stu;
    handle_student(handle);
    free_student(stu);
    return 0;
}

你可能感兴趣的:(c)