简体   繁体   中英

Conversion of std::string to c-string mosquitto

I'm using mosquitto to publish some message to a subscriber.

For subscriber I use:

mosquitto_sub -h host -t "new_topic" -q 0

Instead, for publish I develop a program that uses mosquittopp wrapper, but isn't relevant.

I send message using this method:

int MyClass::publish(const char* message) {
    return mosquittopp::publish(NULL, topic_, strlen(message),
            (uint8_t*) message, qos_);
}
....
MyClass publisher;
string s = base64_decode("LAAAtQ8AIXRpwoVyeMKodMK2wpPDscKBYcKDw6jCg8KAYWDDhjVCMQ==");
publisher.publish(s.c_str());

If I print s, I get:

,�!tirx¨t¶ñaèa`Æ5B1  

And I think is ok.

But subscriber seems receiving only first char, in fact print only:

 ,  

Any ideas?

update

It was a BUG on version I used (1.3.1), fixed from version 1.3.4.

The second character of the decoded string has the value zero. That's used to mark the end of a C-style string; so strlen will report a length of 1 upon finding a zero after one character.

If you want to use "strings" containing null characters, you can't use the C library's null-terminated string handling functions. I'd change MyClass::publish to work with a C++ string (or perhaps std::vector<uint8_t> so that it won't be mistaken for a printable string), so the length is available as message.size() whether or not it contains null characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM