Sending data between erlang and c ++

I use tcp connection to send data to a C ++ server. I read about the ei library, which, when given a binary, has a bunch of functions to get the decoded value from the binary. Egs, ei_decode_string, ei_decode_long and others.

I am trying to do these simple things:
1. Create a socket and connect to it.

{ok, Socket} = gen_tcp:connect({127,0,0,1}, 8986, []). 

2. Use gen_tcp: send / 2 to send data.

 gen_tcp:send(Socket, term_to_binary("Stackoverflow")). 

Therefore, I am sending the binary string format to the server.

My server, C ++ code, receives the data, and I'm trying to get what the client sends to me through the socket using ei_decode_string, for example:

Ideally, when decoding, I should return the string "Stackoverflow", as I told her decode_as_string from the binary. Make sure I have enough space in the resulting buffer.

 char *p = (char*)malloc(sizeof(char) * 100); int index = 0; int decoded = ei_decode_string(buff, &index, p); cout<<"The decoded value is "<<p<<endl; 

I can not decode the string I sent.! Am I missing something? How can I send data and decode it on the server side if this is the wrong approach.

Thanks for the help!

+5
source share
1 answer
 1> term_to_binary("Stackoverflow"). <<131,107,0,13,83,116,97,99,107,111,118,101,114,102,108, 111,119>> 

Here, the first element in binary expression is not a string as small integers, but a version number (131), as described in the External format of the term . After this, terms appear, each of which has a tag prefix, and then the corresponding data. In this case, tag 107 STRING_EXT , two bytes for the length (13), and then 13 8-bit integers, the first of which 83 corresponds to the letter "S" (83 in ascii).

To handle this binary correctly, an ei_decode_version call must be before ei_decode_string

int ei_decode_version (const char * buf, int * index, int * version)

This function decodes the magic version number for the erlang binary long-term format. This must be the first token in the binary member.

0
source

Source: https://habr.com/ru/post/1247474/


All Articles