【问题标题】:How to extract the size of a type from a binary without running or using special tools如何在不运行或使用特殊工具的情况下从二进制文件中提取类型的大小
【发布时间】:2022-01-10 13:23:26
【问题描述】:

我想从目标文件/库中提取某些类型的大小

  • 不运行二进制文件
  • 无需特殊工具
  • 适用于任何工具链(GNU、MSVC、IAR)

我想采用presented here 的方法,但采用更通用的形式。

理想情况下它会像这样工作:


// Some file.cpp
class MyClass {
    // lots of members
};

#include "SizeInfo.h"
const SizeInfo<MyClass, "MyIdentifier"> info;

我会将SizeInfo 放在任何我对字体大小感兴趣的地方。我可能对每个翻译单元的多种类型感兴趣。解决方案应该将字符串 SizeOf MyIdentifier:1234 放入生成的目标文件中,以便我可以使用 grep 之类的简单工具提取标识符和大小。预计该变量会从生成的可执行文件或共享库中丢弃,因为它没有在任何地方使用。

我在我的项目中使用了 boost,所以如果这样可以简化实现,我完全赞成。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    这给出了一个类型的大小(以字节为单位):

    sizeof(MyClass)
    

    【讨论】:

      【解决方案2】:

      我认为应该可以简单地使用常规sizeof 获取类型的大小,然后通过可变参数模板将数字转换为字符串,如this post 中所述。

      然后你可以从你的目标文件中导出一个字符串变量并在外面用grep查找它。

      它应该像这样工作: 尺寸信息.h:

      namespace detail
      {
          template<unsigned... digits>
          struct to_chars { static const char value[]; };
      
          template<unsigned... digits>
          constexpr char to_chars<digits...>::value[] = {('0' + digits)..., 0};
      
          template<unsigned rem, unsigned... digits>
          struct explode : explode<rem / 10, rem % 10, digits...> {};
      
          template<unsigned... digits>
          struct explode<0, digits...> : to_chars<digits...> {};
      }
      
      template<unsigned num>
      struct num_to_string : detail::explode<num> {};
      

      我从this excellent tutorial on static strings下载了头文件static_string.hpp

      一些文件.cpp:

      class MyClass {
          // lots of members
      };
      
      #include "static_string.hpp"
      namespace sstr = ak_toolkit::static_str;
      
      #include "Sizeinfo.h"
      constexpr auto MyClassSize = "MyIdentifier: " + sstr::literal(num_to_string<sizeof(MyClass)>::value);
      

      使用gcc -c Somefile.cpp 编译后,我可以验证目标文件中的以下字符串:MyIdentifier: 8

      【讨论】:

      • 'MyClassSize' 是在编译时组装的吗?
      • 你是对的。它不是。我必须看看如何实现它。给我一分钟。
      • 我成功了!我将编辑我的答案。
      • 完成!请验证更新的信息,我的测试成功了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多