Encoding and decoding erlang data in the C program with ei library

Hello everybody!
I’m passing data from erlang/elixir to a C program using unix domain socket.
I can confirm that I’m receiving the data on the C side but unable to decode it using the ei.h library.
Tried many different decoding functions but all return -1.
I’m using term_to_binary/1 to encode the data on the erlang side.
This is the erlang code for encoding and sending the data.

    {:ok, port} = :gen_udp.open(0, [:binary, {:ifaddr, {:local, client_socket}}])
    msg = 'hello world!' |> :erlang.term_to_binary()
    :gen_udp.send(port, {:local, server_socket}, 0, msg)

This is the C code for receiving the data and decoding it.

	char buff[8192];
	int index, len;
	const char* pp;
	size_t nbitsp;

	while ((len = recvfrom(fd, buff, 8192, 0, (struct sockaddr *)&from, &fromlen)) > 0) {
        index = 0;

		ei_decode_bitstring(buff, &index, &pp, NULL, &nbitsp);
		printf("Received: %s\n", buff);
	}

Just to add I can send binaries without encoding/decoding and print the message on the C side. The reason I’m trying to encode/decode is because I’m planning on sending more complex data strctures to the C program.

This could be more of a C question than erlang but I hope anybody could guide me in the right direction.

Thanks :slight_smile:

2 Likes

A while back I wrote this tutorial that you might find helpful:

4 Likes

Thanks for the article. Was exactly what I was looking for.
Had two problems in my code. First of all I must use byte* buf for the buffer variable and decode the version next using the ei_decode_version(buf, &index, &version).

2 Likes