如何获得具有编码的类型的大小? [英] How can one obtain the sizeof a type for which one has an encoding?

查看:58
本文介绍了如何获得具有编码的类型的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个Objective-C类型type,可以获得encoding encodingsize 类型的大小很容易:

Given an Objective-C type type, one can obtain the encoding encoding and size size of the type easily:

const char *encoding = @encode(type);
size_t size = sizeof(type);

换一种说法,我们有映射

Put a little differently, we have mappings

@encode: type_t -> const char *
sizeof:  type_t -> size_t

这引发了两个问题:

(1) 假设我们没有类型,而只有编码.获得映射会很好

(1) Suppose that rather than having a type, we have only an encoding. It would be nice to obtain a mapping

sizeofencodedtype: const char * -> size_t

这样对于每个 type_t type 我们都有

such that for every type_t type we have that

sizeofencodedtype(@encode(type)) = sizeof(type)

这样的功能已经存在了吗?如果没有,人们怎么可能去建造一个?

Does such a function already exist? If not, how might one go about building one?

(2) 理想情况下,我们可以反转 @encode 映射以进行映射

(2) Ideally we could invert the @encode mapping to make a mapping

decode: const char * -> type_t

但这似乎不可能,因为 type_t 不是真正的 C 类型.我想我可以等待 @decode 被添加到语言中,但这不是很现实或对时间敏感.但是在运行时使用它的编码实例化一个类型是不可能的吗?

but this doesn't seem to be possible since type_t isn't a real C type. I guess I could wait for @decode to be added to the language, but that's not very realistic or time-sensitive. But should it not be possible to instantiate a type at runtime using its encoding?

参考资料:Objective-C 运行时编程指南 - 类型编码

推荐答案

NSGetSizeAndAlignment() 可以为您做到这一点.如果您试图在同一个字符串中探索多种类型,它也是一个有用的函数.

NSGetSizeAndAlignment() can do this for you. It's also a useful function if you're trying to grope through multiple types in the same string.

这篇关于如何获得具有编码的类型的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆