Codebase list libmawk / a8c8f483-bda4-4dcb-b181-d7b9964ade2c/main src / example_apps / 70_c_func / app.c

Tree @a8c8f483-bda4-4dcb-b181-d7b9964ade2c/main (Download .tar.gz)

app.c @a8c8f483-bda4-4dcb-b181-d7b9964ade2c/mainraw · history · blame

#include <stdio.h>
#include <libmawk.h>

	Purpose: implement a C function that can be called from the script.
	Run: ./app -f test.awk

/* sp is the stack pointer, a_args is the number of arguments on the stack */
mawk_cell_t *blobb(mawk_state_t *context, mawk_cell_t *sp, int num_args)
	int n;
	char buff[64];

	/* do something - print BLOBB and all arguments */
	printf("BLOBB! ");
	for(n = 0; n < num_args; n++)
		printf("arg%d='%s' ", n, libmawk_print_cell(context, libmawk_cfunc_arg(sp, num_args, n), buff, sizeof(buff)));

	/* set a return value (find out where the return value is on the stack,
	   using libmawk_cfunc_ret()) */
	libmawk_set_cell(context, libmawk_cfunc_ret(sp, num_args), 'f', (double)1234);

	/* return the new stack pointer - should be the one that was before
	   arguments had been pushed on the stack */
	return sp - num_args;

int main(int argc, char **argv)
	mawk_state_t *m;

	/* init a context, execute BEGIN */
	m = libmawk_initialize(argc, argv);
	if (m == NULL) {
		fprintf(stderr, "libmawk_initialize failed, exiting\n");
		return 1;

	/* The function is registered after BEGIN is run by libmawk_initialize;
	   this means the script can not call the function from BEGIN. If calling
	   from BEGIN is required, the 3-stage initialization shall be implemented,
	   the function registered between stage1 and stage2. */

	/* register a C function (resolved runtime) */
	if (libmawk_register_function(m, "blobb", blobb) != 0) {
		fprintf(stderr, "app: ERROR: Unable to register function blobb\n");
		return 1;

	/* run END and free the context */

	return 0;