从字符串中获取结构的大小

Getting the size of a struct from a string

本文关键字:结构 获取 字符串      更新时间:2023-10-16

我有以下内容:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string> 
struct headerStruct{
uint8_t header;
uint8_t data_1;
uint8_t data_2;
uint8_t data_3;
uint8_t data_4;
} my_header_0;
struct headerStruct2{
uint8_t data_8;
uint8_t data_9;
} my_header_1;
int main(void)
{
std::stringstream ss;
for(int i=0; i < 2; i++)   
{
ss.str("");
ss << "my_header_" << i;
std::cout << "size of struct: " << sizeof(ss) << std::endl; // I know this line will be wrong but you get what I want to do, I want the size to output 5 and 2 for this example
}
}

有时我会想迭代我拥有的头的数量,即my_header_0、my_header_1。。。my_header_n。这就是为什么我试着把它放在字符串流ss中,这样我就可以编辑字符串并调用sizeof函数。有时我会有更多版本的my_header_n,n是任何数字,每个数字都有不同的大小。然而,我还不确定如何实施这一点。

上面示例代码的输出是:

size of struct: 248
size of struct: 248

我知道248是ss对象本身的大小。

但是,我希望我的输出是

size of struct: 5
size of struct: 2

这实际上是上面列出的结构的大小。

这可能吗?或者任何推荐的获得预期输出的方法。

我会构建一个映射,其中包含所有具有要检查的名称的对象。然后使用预处理器宏将名称转换为字符串。

#include <iostream>
#include <map>
#include <stddef.h>
#include <sstream>
#include <string>
struct headerStruct {
uint8_t header;
uint8_t data_1;
uint8_t data_2;
uint8_t data_3;
uint8_t data_4;
} my_header_0;
struct headerStruct2 {
uint8_t data_8;
uint8_t data_9;
} my_header_1;
// preprocessor macro to convert something into a string
#define getname(n) #n
// map storing the sizes
std::map<const std::string, size_t> map( {{getname(my_header_0), sizeof(my_header_0)},
{getname(my_header_1), sizeof(my_header_1)}});

int main(int argc, char * argv[]) {
for(auto n : map) {
std::cout << n.first << " is of size: " << n.second << std::endl;
}
std::stringstream ss;
for(int i = 0; i < 2; ++i) {
ss.str("");
ss << "my_header_" << i;
// get the size from the map
std::cout << "size_of_struct "" << ss.str() << "": " << map[ss.str()] << std::endl;
}
return 0;
}

或者使用更多的对象定向并将对象本身存储在数据库中,给它们一个大小函数,然后我们开始。。。

#include <iostream>
#include <map>
#include <stddef.h>
#include <sstream>
#include <string>
struct base {
virtual size_t size() { return 0; }
};
struct headerStruct : public base {
uint8_t header;
uint8_t data_1;
uint8_t data_2;
uint8_t data_3;
uint8_t data_4;
virtual size_t size() { return 5; }
} my_header_0;
struct headerStruct2 : public base {
uint8_t data_8;
uint8_t data_9;
virtual size_t size() { return 2; }
} my_header_1;
// preprocessor macro to convert something into a string
#define getname(n) #n
std::map<const std::string, struct base &> map( {{getname(my_header_0), my_header_0},
{getname(my_header_1), my_header_1}});

int main(int argc, char * argv[]) {
for(auto n : map) {
std::cout << n.first << " is of size: " << n.second.size() << std::endl;
}
return 0;
}