Asterisk - The Open Source Telephony Project
18.5.0
|
String fields in structures
This file contains objects and macros used to manage string fields in structures without requiring them to be allocated as fixed-size buffers or requiring individual allocations for for each field.
Using this functionality is quite simple. An example structure with three fields is defined like this:
When an instance of this structure is allocated (either statically or dynamically), the fields and the pool of storage for them must be initialized:
Fields will default to pointing to an empty string, and will revert to that when ast_string_field_set() is called with a NULL argument. A string field will never contain NULL.
ast_string_field_init(x, 0) will reset fields to the initial value while keeping the pool allocated.
Reading the fields is much like using 'const char * const' fields in the structure: you cannot write to the field or to the memory it points to.
Writing to the fields must be done using the wrapper macros listed below; and assignments are always by value (i.e. strings are copied): ast_string_field_set() stores a simple value; ast_string_field_build() builds the string using a printf-style format; ast_string_field_build_va() is the varargs version of the above; variants of these function allow passing a pointer to the field as an argument.
When the structure instance is no longer needed, the fields and their storage pool must be freed:
A new feature "Extended String Fields" has been added in 13.9.0.
An extended field is one that is declared outside the AST_DECLARE_STRING_FIELDS block but still inside the parent structure. It's most useful for extending structures where adding a new string field to an existing AST_DECLARE_STRING_FIELDS block would break ABI compatibility.
Example:
Adding "blah" to the existing string fields breaks ABI compatibility because it changes the offsets of x1 and x2.
However, adding "blah" as an extended string field to the end of the structure doesn't break ABI compatibility but still allows the use of the existing pool.
The only additional step required is to call ast_string_field_init_extended so the pool knows about the new field. It must be called AFTER ast_string_field_init or ast_calloc_with_stringfields. Although ast_calloc_with_stringfields is used in the sample below, it's not necessary for extended string fields.
The new field can now be treated just like any other string field and it's storage will be released with the rest of the string fields.
This completes the API description.