Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to manually calculate the byte-offset of a class member?

That is, what is the standard a compiler uses to generate a class? For example, let's say that I have class C with members x, y, and z, and I want to know the offset of z within that class. Can I just add up the data-type sizes of the other members, like I would for a structure?

like image 460
Jim Fell Avatar asked Jul 13 '11 16:07

Jim Fell


People also ask

How do you calculate byte offset?

The byte offset is just the count of the bytes, starting at 0. The big question is: how are the 16-bit offsets for the branch instructions calculated. The big answer is: count the number of bytes to the destination. The first branch is in instruction 7 in the IJVM code, and at offset 11 in the hex byte code.

What is bytecode offset?

The bytecode offset is the byte offset into the Java method identified by method number at which the error occurs. The reason code indicates the specific reason for the exception, and is one of the following: Reason Code. Meaning. 00000001.

How many bytes is an offset?

In computer science, offset describes the location of a piece of data compared to another location. For example, when a program is accessing an array of bytes, the fifth byte is offset by four bytes from the array's beginning.


2 Answers

No You cannot.
Compilers are free to align the members as they chose to.It is an implementation detail of the compilers.

If you're working with a POD, then you can use the offsetof macro.

But If working with a Non-POD, then I suppose there won't be any portable method to do so.

like image 165
Alok Save Avatar answered Sep 26 '22 00:09

Alok Save


You can do it programatically like this in a method of the class. Not generic but works.

offset = (unsigned char*)&(this->z) - (unsigned char*)this;

Full working example

#include <iostream>

class C
{
public:
    int x;
    char y;
    int z;
    size_t offset() const
    {
        return (unsigned char*)&(this->z) - (unsigned char*)this;
    }
};

int main()
{
    C c;
    std::cerr << "Offset(cast): " << c.offset() << "\n";
}
like image 20
Sodved Avatar answered Sep 26 '22 00:09

Sodved