简体   繁体   English

结构内向量元素的数据字节偏移量

[英]Data byte offset of elements of a vector inside a struct

If I have a struct with members int a, b, c;如果我有一个struct ,其成员int a, b, c; , I can get the byte offset of each member using offsetof(structName, member) . ,我可以使用offsetof(structName, member)获取每个成员的字节偏移量。

Now, if I have a struct with a vector<int> { a, b, c } , I can get the offset of the vector using offsetof(structName, vectorName) .现在,如果我有一个带有vector<int> { a, b, c } struct ,我可以使用offsetof(structName, vectorName)获取vector的偏移量。

Knowing this, is this operation:知道了这个,是不是这个操作:

offsetof(structName, vectorName) + sizeof(vector<int>) + sizeof(int)*2

a valid way of getting the offset of b ?获取b偏移量的有效方法?

First off, b is the vector 's 2nd element, but sizeof(int)*2 would return the offset of the 3rd element instead.首先, bvector的第二个元素,但sizeof(int)*2将返回第三个元素的偏移量。

But more importantly, the vector 's element array is not stored inside the vector class itself, so using offsets relative to the vector itself will not work.但更重要的是, vector的元素数组并不存储在vector class 本身内部,因此使用相对于vector本身的偏移量是行不通的。 The actual array is stored elsewhere in memory, and then the vector contains an internal member that is a pointer to the array.实际数组存储在 memory 中的其他位置,然后该vector包含一个内部成员,该成员是指向该数组的指针。

As such, all you really need to determine the offset of an element in the vector 's array is sizeof(vector::value_type) * index (where index is 1 for b in your example).因此,您真正需要确定vector数组中元素的偏移量的是sizeof(vector::value_type) * index (在您的示例中,对于b而言, index为 1)。 However, to actually access the element using that offset, you first need the pointer to the array itself.但是,要使用该偏移量实际访问元素,您首先需要指向数组本身的指针。 You can use the vector 's data() method, or operator[] , to get that pointer, eg:您可以使用vectordata()方法或operator[]来获取该指针,例如:

structName *s = ...;
vector<int> *v = reinterpret_cast<vector<int>*>(
    reinterpret_cast<unsigned char*>(s)
    + offsetof(structName, vectorName)
);
int *arr = v->data();
// or: int *arr = &(*v)[0];
size_t offset = sizeof(int) * index;
int *element = reinterpret_cast<int*>(
    reinterpret_cast<unsigned char*>(arr)
    + offset
);
// use element as needed...

However, you really shouldn't use offsetof like this.但是,您真的不应该像这样使用offsetof The above can be greatly simplified to this instead:上面可以大大简化为:

structName *s = ...;
int *element = s->vectorName.data() + index;
// or: int *element = &(s->vectorName[index]);
// use element as needed...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM