0
votes

I have a c++ code which receives data from an erlang process. I get a tuple and using ei_decode_tuple_header/4, I got the arity of the list and then using a for-loop to traverse through the elements of the tuple and decode each one of them like this:

void decode_tuple(char *buff) {
   int index = 0;
   int size;
   int type;
   int res = ei_decode_tuple_header(buff, &index, &size);
   if(res == 0) {
     cout<<"Success"<<endl;
   } else {
     cout<<"Fail"<<endl;
   }

  for(int i = 0; i < size; ++i) {
    char *p = (char*)malloc(sizeof(char) * 1000);
    int res = ei_decode_string(buff, &index, p);
    if(res == 0) {
        cout<<"Success"<<endl;
    } else {
        cout<<"Fail"<<endl;
    }
    cout<<"The decoded string is "<<p<<endl;
    }
  }

However, this works only fine when all of the elements in the tuple/list are of the same type. I would like to decode no matter what the term is. I know that there is ei_decode_term but the documentation is so bad that I could not get an idea as to how to do it?

Can some one help! thanks@

1

1 Answers

0
votes

Have you tried with ei_decode_ei_term, something like:

void decode_tuple(char *buff) {
  int index = 0;
  int size;
  int type;
  int res = ei_decode_tuple_header(buff, &index, &size);

  if(res == 0) {
    cout << "Success" << endl;
  } else {
    cout << "Fail" << endl;
  }

  for(int i = 0; i < size; ++i) {
    ei_term term;
    int res = ei_decode_ei_term(buff, &index, &term);
    if (res == 0) {
      cout << "Success" << endl;
    } else {
      cout << "Fail" << endl;
    }
    cout << "The decoded data is " << term.value << endl;
  }
}

The ei_term is defined like:

typedef struct {
    char ei_type;
    int arity;
    int size;
    union {
        long i_val;
        double d_val;
        char atom_name[MAXATOMLEN_UTF8];
        erlang_pid pid;
        erlang_port port;
        erlang_ref ref;
    } value;
} ei_term;

So you may need to check term.ei_type for better parsing