3

我正在阅读 lua (5.3.0) 的源代码,lobject.h我发现它使用一种奇怪的方法来操作字符串,如下所示:

/*
 ** Header for string value; string bytes follow the end of this structure
 ** (aligned according to 'UTString'; see next).
 */
 typedef struct TString {
     CommonHeader;
     lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
     unsigned int hash;
     size_t len;  /* number of characters in string */
     struct TString *hnext;  /* linked list for hash table */
} TString;


/*
** Ensures that address after this type is always fully aligned.
*/
typedef union UTString {
    L_Umaxalign dummy;  /* ensures maximum alignment for strings */
    TString tsv;
}UTString;


/*
 ** Get the actual string (array of bytes) from a 'TString'.
 ** (Access to 'extra' ensures that value is really a 'TString'.)
 */
#define getaddrstr(ts)  (cast(char *, (ts)) + sizeof(UTString))
#define getstr(ts)  \
check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))

关于在那里使用这种方法的原因,我找到了一个很好的答案。但我想知道ensures maximum alignment for strings,这是什么意思?为什么我们需要maximum alignment以及如何确保?

4

0 回答 0