How can one obtain the sizeof a type for which one has an encoding?

这一生的挚爱 提交于 2019-12-05 16:41:48

问题


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

This raises two questions:

(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

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) Ideally we could invert the @encode mapping to make a mapping

decode: const char * -> type_t

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?

References: Objective-C Runtime Programming Guide - Type Encodings


回答1:


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.



来源:https://stackoverflow.com/questions/8281719/how-can-one-obtain-the-sizeof-a-type-for-which-one-has-an-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!