Next: , Previous: Requesting Values, Up: Extension API Description


16.4.4 Constructor Functions and Convenience Macros

The API provides a number of constructor functions for creating string and numeric values, as well as a number of convenience macros. This subsection presents them all as function prototypes, in the way that extension code would use them.

static inline awk_value_t *
make_const_string(const char *string, size_t length, awk_value_t *result)
This function creates a string value in the awk_value_t variable pointed to by result. It expects string to be a C string constant (or other string data), and automatically creates a copy of the data for storage in result. It returns result.
static inline awk_value_t *
make_malloced_string(const char *string, size_t length, awk_value_t *result)
This function creates a string value in the awk_value_t variable pointed to by result. It expects string to be a ‘char *’ value pointing to data previously obtained from malloc(). The idea here is that the data is passed directly to gawk, which assumes responsibility for it. It returns result.
static inline awk_value_t *
make_null_string(awk_value_t *result)
This specialized function creates a null string (the “undefined” value) in the awk_value_t variable pointed to by result. It returns result.
static inline awk_value_t *
make_number(double num, awk_value_t *result)
This function simply creates a numeric value in the awk_value_t variable pointed to by result.

Two convenience macros may be used for allocating storage from malloc() and realloc(). If the allocation fails, they cause gawk to exit with a fatal error message. They should be used as if they were procedure calls that do not return a value.

#define emalloc(pointer, type, size, message) ...
The arguments to this macro are as follows:
pointer
The pointer variable to point at the allocated storage.
type
The type of the pointer variable, used to create a cast for the call to malloc().
size
The total number of bytes to be allocated.
message
A message to be prefixed to the fatal error message. Typically this is the name of the function using the macro.

For example, you might allocate a string value like so:

          awk_value_t result;
          char *message;
          const char greet[] = "Don't Panic!";
          
          emalloc(message, char *, sizeof(greet), "myfunc");
          strcpy(message, greet);
          make_malloced_string(message, strlen(message), & result);

#define erealloc(pointer, type, size, message) ...
This is like emalloc(), but it calls realloc(), instead of malloc(). The arguments are the same as for the emalloc() macro.