加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用uint64_t作为内存的通用地址而不是void *的利弊是什么

发布时间:2020-12-16 06:53:50 所属栏目:百科 来源:网络整理
导读:我是C编程的新手.我发现uint64_t在libibverbs中用作缓冲区的地址而不是void *. struct ibv_sge{ uint64_t addr; uint32_t length; uint32_t lkey;} 我能想到的一个缺点是它的便携性.在32位系统上,它将导致编译错误或至少浪费内存.那为什么呢?有什么好处吗?
我是C编程的新手.我发现uint64_t在libibverbs中用作缓冲区的地址而不是void *.

struct ibv_sge{
    uint64_t addr;
    uint32_t length;
    uint32_t lkey;
}

我能想到的一个缺点是它的便携性.在32位系统上,它将导致编译错误或至少浪费内存.那为什么呢?有什么好处吗?

我还注意到还有其他替代方法,例如uintptr_t.描述通用内存地址的最佳方法是什么?

解决方法

pros and cons of using uint64_t as an universal address of memory

缺点:

>当通用地址较窄时,可能会有不必要的宽度.
>当需要更广泛的通用地址时,可能会不必要地缩小范围.

C没有通用地址.最接近的是void *,但只指定对象指针就足够了. void *可能不足以用于函数指针.任何函数指针类型与另一个函数指针类型的大小相同.

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer. C11dr §6.3.2.3 1

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. §6.3.2.3 8

What’s the best approach to describe an universal address of memory?

用C代替使用union.

union u_pointer {
  void *obj;
  int (*fun)();
};

读取和写入这些成员的访问权限需要小心处理,就像任何通用指针一样.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读