[erlang-questions] Service Change request in C node

Robert Raschke rrerlang@REDACTED
Wed Feb 13 13:20:47 CET 2008


I haven't used erl_interface in a very long time.  I would use ei
instead these days.  And having dug out some very old code of mine,
here's how I used to decode/encode lists of strings.  Maybe you can
use this as a pointer in the right direction.

In essence, you will need to unpack the list by first figuring out how
many elements are in it, and then traversing the list, getting your
strings.  I'm sure a solution using erl_interface would be reasonably
similar in structure.


#include "ei.h"

void
build_result(ei_x_buff *args, ei_x_buff *result)
{
	int n=0;
	char **s_array=NULL;
	int k;

	if (ei_decode_list_header(args->buff, &args->index, &n) < 0) {
		error();
		return;
	}
	if (n > 0) {
		if ((s_array = decode_string_list(args->buff, &args->index, n)) == NULL) {
			error();
			return;
		}
	}

	/* result is list of strings */
	for (k = 0; k < n; k++) {
		ei_x_encode_list_header(result, 1);
		ei_x_encode_string(result, s_array[k]);
	}
	ei_x_encode_empty_list(result);
}

char **
decode_string_list(const char *buff, int *index, int n)
{
	int i;
	int type;
	int len;
	int arity;
	char **s_array = (char **) calloc(n, sizeof(char *));
	
	for (i = 0; i < n; i++) {
		ei_get_type(buff, index, &type, &len);
		s_array[i] = (char *) malloc(len + 1);
		if (ei_decode_string(buff, index, s_array[i]) < 0) {
			free_string_array(s_array, i+1);
			return NULL;
		}
	}
	/* Trailing [] (NIL). */
	if (ei_decode_list_header(buff, index, &arity) < 0
	    || arity != 0) {
		free_string_array(s_array, n);
		return NULL;
	}

	return s_array;
}

void
free_string_array(char **s_array, int n)
{
	int i;
	
	for (i = 0; i < n; i++) {
		free(s_array[i]);
	}
	free(s_array);
}


Robby




More information about the erlang-questions mailing list