从虚空转换* C++中
我在MQTT应用程序的工作,并为int当我收到来自MQTT经纪人有效载荷的信息,并试图将其从void *的是MESSAGE->的有效载荷为int的转换的从虚空转换* C++中
signed int var_1=*((int*) message->payload);
,而不是将其转换为它是将其转换为另一个数,看到这个我使用下面的代码:
printf("Message:%s\n",message->payload);
printf("Message:%i\n",var_1);
其中显示:
Message:-58
Message:3683629
我也想过有效载荷是一个字符串,但如果我用Stoi旅馆功能它给我的错误:
can not convert from ´void*´ to ´int´ with stoi function.
如果MESSAGE->有效载荷持有数量本身还是我没太明白它的字符串表示。 如果MESSAGE->有效载荷保持在其数目被存储在存储器位置,所以VAR_1保持值。 因此,你不能指望这些值是相同的。 关于Stoi旅馆 - 它接收持有数字的字符串,但作为一个字符串。例如 -
std::string num = "1234";
int convertedNumber = stoi(num);
在C++中,不能自动转换从const void*
到const char*
。
你需要一个明确的静态浇铸:
int i=atoi(static_cast<const char*>(message->payload));
通知我用atoi()
这是一个C库函数(#include <cstdlib>
)。
将它转换为std::string
只是为了将其解析为int
。
这一切都假定你是正确的思考有效载荷是一个C风格字符串的字符编码的十进制整数。
OK。第一步是找出正在运输的物体的类型。作为MQTT的文件说:
MQTT is data-agnostic and it totally depends on the use case how the payload is structured. It’s completely up to the sender if it wants to send ...
as
signed int var_1=*((int*) message->payload);
现在,这是正确的,如果指针指向int
类型的对象。这是一个合理的猜测,但你不应该猜测 - 除了作为最后的手段 - 对象的类型。您应该通过阅读文档或代码来研究发件人,以确定指出的对象的类型。
instead of converting it to the number it is converting it to another one
所以,要么你一直在期待错误的值,要么你猜错了类型。解决方案是停止猜测并找出正确的类型。
I also thought about the payload being a string, but if I use the stoi function it gives me the error:
can not convert from ´void*´ to ´int´ with stoi function.
的错误似乎是非常清楚的。 stoi
的论点是const std::string& str
,而不是void*
。 void*
不能隐式转换为std::string
。究竟如何做这样的转换取决于什么类型的对象void*
指向(或有时,它是什么类型的数据它包含)。
你到底在问什么?无论如何,'message-> payload'应该是什么?代表“int”或ascii字符串的缓冲区? –
真正的问题是,消息是如何发送的?发件人做了一些从他的数据中创建一个有效载荷。你需要扭转这个过程。 –
'而不是将其转换为它将其转换为另一个的数字'您期望的数字是多少? – user2079303