cstringvoid-pointersnanopb

Encode/decode strings inside byte type in nanopb with C


I have a .proto file that looks like this:

message ObjValue
{
// ...
    optional bytes byteval    = 6 [max_size = 256]; // arbitrary structure or message
// ...

I use this proto encoding to send structs that change. This struct basically contains ints and strings (a null-terminated char array).

The sender sends the struct doing something like this:

   // Here I create the struct and fill it with integers and strings
   struct flow_msg *flow_msg = malloc(sizeof(struct flow_msg));
    flow_msg->dst_addr        = 1;
    flow_msg->src_addr        = 2;
    flow_msg->src_ap_name     = strdup(src_ap_name);

    // Here I save the length of the struct and a void pointer that points to the struct
    struct ser_obj_value *obj_value = malloc(sizeof(struct ser_obj_value));
    obj_value->size = sizeof(struct flow_msg) + strlen(src_ap_name) + 1; // +1 because of '\0'
    obj_value->data = flow_msg;

Then, the receiver gets the message, decodes it using nanopb and then:

int
handle_msg(void *f_msg)
{
    struct flow_msg *flow_msg = (struct flow_msg *)f_msg;
}

At that point, if I try to read the value of an integer there's no problem (flow_msg->dst_addr, for example), but if I want to read the string value, I get a null pointer because the flow_msg->src_ap_name is empty.

I'm lost in terms of how I should properly encode/decode the string value... Really don't know what I'm missing here... Any clues?


Solution

  • First, I realize now how silly my question was. Actually, I'm not deleting it because @jpa took some time to try to answer my doubts.

    Mainly the problem was that I was trying to send pointers (i.e., memory addresses) and then the receiver of course did not know what to do with this random memory address. Also, the problem was that I was "unlucky" that probably because I was using the same machine and same compiler in the receiver side some pointers were actually properly dereferenced, and that confused me a lot.