0

我有一个如下所示的代码:

typedef struct{
    uint8_t distance[2];
    uint8_t reflectivity;      
}data_point;

typedef struct{
    uint8_t flag[2];
    uint8_t Azimuth[2];
    std::vector<data_point> points; // always size is 32 but not initialized whereas filled in run-time using emplace_back
}data_block;

typedef struct{
    uint8_t UDP[42];
    std::vector<data_block> data; // always size is 12 but not initialized whereas filled in run-time using emplace_back
    uint8_t time_stamp[4];
    uint8_t factory[2];
}data_packet;

static std::vector<data_packet> packets_from_current_frame;

假设packets_from_current_frame.size() = 26,我如何计算其中的字节数packets_from_current_frame

我在纸上的解决方案:

1 data_packet(假设 32points和 12 data)将有42+ (12*(2+2+32(3))) + 4 + 2 = 1248. 因此,结束地址是_begin + sizeof(uint8_t) * 26 * 1248_begin是内存缓冲区的起始地址)。

通过这个计算,我总是会丢失一些数据。丢失的字节数取决于packets_from_current_frame.size()。计算有什么问题?

4

1 回答 1

3

看看这段代码:

int main() {
    static std::vector<data_packet> packets_from_current_frame;

    std::cout << "sizeof data_point  = " << (sizeof(data_point)) << std::endl;
    std::cout << "sizeof data_block  = " << (sizeof(data_block)) << std::endl;
    std::cout << "sizeof data_packet = " << (sizeof(data_packet)) << std::endl;
    return 0;
}

输出:

sizeof data_point  = 3
sizeof data_block  = 32
sizeof data_packet = 80

从这里很清楚为什么你的计算失败了。

您忘记了考虑向量本身、向量之后的字段和填充等因素。

正确的计算方法是:

packets_from_current_frame.size() * (sizeof(data_packet) + data.size() * (sizeof(data_block) + points.size() * sizeof(data_point)))

注意:此字节数不会存储在一个连续的内存块中,因此不要尝试任何直接 memcpy。

单个向量具有连续数据。如果你想知道一个向量持有的数据的地址,使用vector::data()

于 2019-09-18T16:30:42.343 回答