在分析PostgresSQL源码时,有时候需要知道某些结构体、变量的大小,如果只是从字面来看又无法确定变量的大小,那这个时候可以借助C语言来实现这需求,比如下面的结构体:
typedef struct PageHeaderData
{
/* XXX LSN is member of *any* block, not only page-organized ones */
PageXLogRecPtr pd_lsn; /* LSN: next byte after last byte of xlog
* record for last change to this page */
uint16 pd_checksum; /* checksum */
uint16 pd_flags; /* flag bits, see below */
LocationIndex pd_lower; /* offset to start of free space */
LocationIndex pd_upper; /* offset to end of free space */
LocationIndex pd_special; /* offset to start of special space */
uint16 pd_pagesize_version;
TransactionId pd_prune_xid; /* oldest prunable XID, or zero if none */
ItemIdData pd_linp[FLEXIBLE_ARRAY_MEMBER]; /* line pointer array */
} PageHeaderData;
如果现在想知道ItemIdData变量占用几个字节?可以用如下的方式获取
cat get.c
get.c文件放在源码下的/src/include下面
#include "postgres.h"
#include <string.h>
#include <stdio.h>
#include <storage/bufpage.h>
typedef PageHeaderData P;
typedef ItemIdData I;
int main(int argc, char **argv)
{
// typedef struct PageHeaderData
// {
// /* XXX LSN is member of *any* block, not only page-organized ones */
// PageXLogRecPtr pd_lsn; /* LSN: next byte after last byte of xlog
// * record for last change to this page */
// uint16 pd_checksum; /* checksum */
// uint16 pd_flags; /* flag bits, see below */
// LocationIndex pd_lower; /* offset to start of free space */
// LocationIndex pd_upper; /* offset to end of free space */
// LocationIndex pd_special; /* offset to start of special space */
// uint16 pd_pagesize_version;
// TransactionId pd_prune_xid; /* oldest prunable XID, or zero if none */
// ItemIdData pd_linp[FLEXIBLE_ARRAY_MEMBER]; /* line pointer array */
//} PageHeaderData;
P p;
I i;
printf("pd_lsn=%d\n", sizeof(p.pd_lsn));
printf("pd_checksum=%d\n", sizeof(p.pd_checksum));
printf("pd_flags=%d\n", sizeof(p.pd_flags));
printf("pd_lower=%d\n", sizeof(p.pd_lower));
printf("pd_upper=%d\n", sizeof(p.pd_upper));
printf("pd_special=%d\n", sizeof(p.pd_special));
printf("pd_pagesize_version=%d\n", sizeof(p.pd_pagesize_version));
printf("pd_prune_xid=%d\n", sizeof(p.pd_prune_xid));
printf("ItemIdData=%d\n", sizeof(i));
return 0;
}
使用PostgresSQL的头文件编译get.c文件
gcc -I`pg_config --includedir-server` -fPIC -c get.c
gcc -o get get.o
执行get文件
[postgres@postgres include]$ ./get
pd_lsn=8
pd_checksum=2
pd_flags=2
pd_lower=2
pd_upper=2
pd_special=2
pd_pagesize_version=2
pd_prune_xid=4
ItemIdData=4
[postgres@postgres include]$
这样就可以获取结构体里面各个变量的大小