Store data in a varying-length structure
The mi_set_vardata() and mi_set_vardata_align() functions copy data into an existing data portion of a varying-length structure. These functions assume that the data portion is large enough to hold the data being copied.
#define TEXT_LENGTH 200
...
mi_lvarchar *new_lvarch;
mi_char *local_var;
...
/* Allocate a new varying-length structure with a 200-byte
* data portion
*/
new_lvarch = mi_new_var(TEXT_LENGTH);
/* Allocate memory for null-terminated string */
local_var = (char *)mi_alloc(TEXT_LENGTH + 1);
/* Create the varying-length data to store */
sprintf(local_var, "%s %s %s", "A varying-length structure ",
"stores data in a data portion, which is separate from ",
"the varying-length structure.");
/* Update the data length to reflect the string length */
mi_set_varlen(new_lvarch, stleng(local_var));
/* Store the varying-length data in the varying-length
* structure that new_lvarch references
*/
mi_set_vardata(new_lvarch, local_var);
In the preceding code fragment, the call to mi_new_var() creates a new varying-length structure and sets the length field to 200. This call also allocates the 200-byte data portion (see Figure 2).
The mi_set_vardata() function copies from the local_var buffer the number of bytes that the data length specifies. Your code must ensure that the data-length field contains the number of bytes you want to copy. In the code fragment in Figure 1, the data-length field was last set by the call to mi_set_varlen() to 110 bytes. However, if the mi_set_varlen() function executed after the mi_set_vardata() call, the data length would still have been 200 bytes (set by mi_new_var()). In this case, mi_set_vardata() would try to copy 200 bytes starting at the location of the local_var variable. Because the actual local_var data only occupies 110 bytes of memory, 90 unused bytes remain in the data portion.
char *buff;
mi_lvarchar *var_struc;
...
mi_set_vardata_align(var_struc, buff, 8);
The mi_set_vardata_align() function copies the number of bytes that the data-length field specifies.