I’m using a Azure IoT Hub to send and receive messages to and from a device. To do this, I’m utilizing a library written in C and my application is written in C++. When I convert my std::string to a char* with the data() function to send a message with the C library, the start of the text gets mangled when I receive it in the hub.
The library’s send function expects a struct like this when sending a message from the device to the cloud:
struct azure_iot_hub_buf {
/* Pointer to buffer. */
char *ptr;
/* Size of buffer. */
size_t size;
};
Defining the message like this:
char* message = ""This is a long test string to test the functionality"";
struct azure_iot_hub_buf payload;
payload.ptr = message;
payload.size = strlen(message);
seems to work, when testing in my Azure hub I receive this message:
(https://i.sstatic.net/HWpUfgOy.png)
However, the message I’m sending is not static and is of type std::string so I would like to define it like this:
std::string message = get_message(); // Gets some string message
result.ptr = message.data();
result.size = strlen(message);
but when I receive the message in Azure IoT Hub the start of the text gets mangled:
(https://i.sstatic.net/pAFSA5fg.png)
Looking at this, I thought that I must be doing something wrong, the message I’m sending is obviously getting altered when I’m assigning it so I debugged my firmware found the raw memory of the variable right before sending the message:
(https://i.sstatic.net/82ohL3aT.png)
But it seems like the messages are identical. The only difference I can see, is that the char* is allocated on the stack as it is defined compile time, while the std::string is allocated in RAM as it is defined at runtime. Could this cause any problems I’m not aware of?
Nils Rasmussen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.