C言語の構造体のオフセットを求めるには

なすうまうま

Perlをインストールしてpstructコマンドを使うと便利です。
例えば、dev/apm/apmio.hで定義されているstruct apm_power_infoのオフセットは、こんな感じで求められます(sys/types.hも指定してあげないとエラーになります。下の例は読み易いように整形しています)。

$ pstruct /usr/include/sys/types.h /usr/include/dev/apm/apmio.h
...
struct apm_power_info {
  double             apm_power_info.battery_state      0       1
  double             apm_power_info.ac_state           1       1
  double             apm_power_info.battery_life       2       1
  double             apm_power_info.spare1             3       1
  struct complex int apm_power_info.minutes_left       4       4
    int              apm_power_info.minutes_left.real  4       4
    int              apm_power_info.minutes_left.imag  8       4
  struct complex int apm_power_info.nbattery           8       4
    int              apm_power_info.nbattery.real      8       4
    int              apm_power_info.nbattery.imag     12       4
  struct complex int apm_power_info.batteryid         12       4
    int              apm_power_info.batteryid.real    12       4
    int              apm_power_info.batteryid.imag    16       4
  struct complex int apm_power_info.spare2[4]         16      16
    int              apm_power_info.spare2.real       16       4
    int              apm_power_info.spare2.imag       20       4
}
...

参考までにstruct apm_power_infoの元々の定義はこちらです。

struct apm_power_info {
        u_char battery_state;
        u_char ac_state;
        u_char battery_life;
        u_char spare1;
        u_int minutes_left;             /* estimate */
        u_int nbattery;         
        u_int batteryid;
        u_int spare2[4];
};