Pau*_*ner 8 c string lua struct
我想要一个简单的字符串表,它将存储一堆常量,我想"嘿!Lua那样做,让我使用一些函数!"
这主要是在lstring.h/lstring.c文件中(我使用的是5.2)
我将首先展示我很好奇的代码.它来自lobject.h
/*
** Header for string value; string bytes follow the end of this structure
*/
typedef union TString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */
struct {
CommonHeader;
lu_byte reserved;
unsigned int hash;
size_t len; /* number of characters in string */
} tsv;
} TString;
/* get the actual string (array of bytes) from a TString */
#define getstr(ts) cast(const char *, (ts) + 1)
/* get the actual string (array of bytes) from a Lua value */
#define svalue(o) getstr(rawtsvalue(o))
Run Code Online (Sandbox Code Playgroud)
如您所见,数据存储在结构之外.要获取字节流,请获取TString的大小,添加1,然后获得char*指针.
这不是很糟糕的编码吗?它在我的C类中被钻进m中以制作明确定义的结构.我知道我可能会在这里搅拌一个巢,但是你真的失去了那么多的速度/空间来定义一个结构作为数据头而不是定义该数据的指针值吗?
这个想法可能是你在一大块数据而不是两个数据中分配标题和数据:
TString *str = (TString*)malloc(sizeof(TString) + <length_of_string>);
Run Code Online (Sandbox Code Playgroud)
除了只调用malloc/free之外,还可以减少内存碎片并增加内存本地化.
但回答你的问题,是的,这些黑客通常是一种不好的做法,应该非常小心.如果你这样做,你可能想要在一层宏/内联函数下隐藏它们.