1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| typedef struct C_strBuf
{
char chars[1];
} C_str;
struct C_strInfo
{
size_t length;
...
/* dernier membre */
struct C_strBuf buf;
};
/* Fonction internes */
struct C_strInfo * C_str_alloc(size_t nCharsInBuf)
{
struct C_strInfo *ret;
size_t fullSize = offsetof(struct C_strInfo, buf)
+ offsetof(struct C_strBuf, chars) /* devrait être zéro */
+ nCharsInBuf * sizeof (ret->buf.chars[0])
;
return malloc(fullSize);
}
/* Fonction de conversion:
Obtient le pointeur qu'on donne à l'utilisateur,
compatible avec printf(). */
C_str * C_str_get_buf(struct C_strInfo *pInfo)
{
return &pInfo->buf;
}
/* Fonction de conversion:
À partir du pointeur qu'on donne à l'utilisateur,
compatible avec printf(),
retrouve le pointeur de la structure complète */
struct C_strInfo * C_str_get_info(C_str *pBuf)
{
char *pbyBuf = (char*)pBuf;
char *pbyInfo = pbyBuf - offsetof(struct C_strInfo, buf);
struct C_strInfo *pInfo = (struct C_strInfo *)pbyInfo;
return pInfo;
} |