Determining struct member byte-offsets at compile-time?

北城余情 提交于 2019-11-28 00:05:20

问题


I want to find the byte offset of a struct member at compile-time. For example:

struct vertex_t
{
    vec3_t position;
    vec3_t normal;
    vec2_t texcoord;
}

I would want to know that the byte offset to normal is (in this case it should be 12.)

I know that I could use offsetof, but that is a run-time function and I'd prefer not to use it.

Is what I'm trying to accomplish even possible?

EDIT: offsetof is compile-time, my bad!


回答1:


offsetof is a compile time constant, if we look at the draft C++ standard section C.3 C standard library paragraph 2 says:

The C++ standard library provides 57 standard macros from the C library, as shown in Table 149.

and the table includes offsetof. If we go to the C99 draft standard section 7.17 Common definitions paragraph 3 includes:

offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes [...]




回答2:


In C:

offsetof is usually actually a macro, and due to its definition, it will probably optimized by the compiler so that it reduces to a constant value. And even if it does become an expression, it is small enough that it should cause almost no overhead.

For example, at the file stddef.h, it is defined as:

#define offsetof(st, m) ((size_t)(&((st *)0)->m))

In C++:

Things get a bit more complicated, since it must resolve offsets for members as methods and other variables. So offsetof is defined as a macro to call another method:

#define offsetof(st, m) __builtin_offsetof(st, m)

If you need it only for structs, you are good enough with offsetof. Else, I don't think it is possible.




回答3:


Are you sure it is run-time?

The following works..

#include <iostream>
#include <algorithm>


struct vertex_t
{
    int32_t position;
    int32_t normal;
    int32_t texcoord;
};

const int i = offsetof(vertex_t, normal); //compile time..

int main()
{
    std::cout<<i;
}

Also see here: offsetof at compile time



来源:https://stackoverflow.com/questions/19943194/determining-struct-member-byte-offsets-at-compile-time

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