std :: vector的前4个字节是什么?

时间:2018-11-24 20:45:13

标签: c++ vector

我想手动读取分配给矢量的值,数量和容量。

通过阅读this,我相信可以通过以下结构手动访问std :: vector

{
  title: "Block",
  type: "block",

  styles: [
    { title: "Normal", value: "normal" },
    { title: "H1", value: "h1" },
    { title: "H2", value: "h2" },
    { title: "H3", value: "h3" },
    { title: "H4", value: "h4" },
    { title: "Quote", value: "blockquote" }
  ],
  lists: [{ title: "Bullet", value: "bullet" }],
  marks: {
    decorators: [
      { title: "Strong", value: "strong" },
      { title: "Emphasis", value: "em" }
    ],
    annotations: [
      {
        title: "URL",
        name: "link",
        type: "object",
        fields: [
          {
            title: "URL",
            name: "href",
            type: "url"
          }
        ]
      }
    ]
  }
}

通过执行以下操作,我可以访问向量中的第一个值。

struct _vector{
    DWORD* begin;
    DWORD* end;
    DWORD* tail;
};

但是,我发现事实并非如此。我需要在结构的顶部添加另一个4字节的值,以便正确地进行开始,结束和尾部的访问地址。下面是我想做的工作版本。

_vector *vec = (_vector*)vectorAddress;
DWORD first_value = vec->begin[0];

程序输出:

#include <iostream>
#include <windows.h>
#include <vector>

std::vector<DWORD> vectorData;

void readVector(DWORD vectorAddress){
    struct _vector{
        DWORD* WHATISTHIS;
        DWORD* begin;
        DWORD* end;
        DWORD* tail;
    };

    _vector* vec = (_vector*)vectorAddress;

    DWORD count = ((DWORD)vec->end - (DWORD)vec->begin) / sizeof(DWORD);
    DWORD capacity = ((DWORD)vec->tail - (DWORD)vec->begin) / sizeof(DWORD);

    printf("Vector has %d items and %d capacity\n", count, capacity);

    for (int i = 0; i < count; i++)
        printf("\tValue at %d is 0x%x\n", i, vec->begin[i]);
}


int main(void){
    vectorData.reserve(3);
    vectorData.push_back(0x123456);
    vectorData.push_back(0x654321);

    while (true){
        readVector((DWORD)&vectorData);
        system("pause");
    }
}

鉴于此,我的_vector结构的前4个字节实际上代表什么?

0 个答案:

没有答案