【问题标题】:invalid conversion from 'byte*' to 'byte'从 'byte*' 到 'byte' 的无效转换
【发布时间】:2015-01-17 22:27:34
【问题描述】:

从 'byte*' 到 'byte' 的无效转换

我已经写了这个arduino函数

byte receiveMessage(AndroidAccessory acc,boolean accstates){
    if(accstates){
        byte rcvmsg[255];
        int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);
        if (len > 0) {
            if (rcvmsg[0] == COMMAND_TEXT) {
                if (rcvmsg[1] == TARGET_DEFAULT){
                byte textLength = rcvmsg[2];
                int textEndIndex = 3 + textLength;
                byte theMessage[textLength];
                int i=0;
                    for(int x = 3; x < textEndIndex; x++) {
                        theMessage[i]=rcvmsg[x];
                        i++;
                        delay(250);
                    }
                return theMessage;
                delay(250);
                }
            }
        }
    }       
}

这是错误

In function byte receiveMessage(AndroidAccessory, boolean) invalid conversion from byte*' to 'byte"

这个函数是从android接收数据并以字节数组的形式返回

【问题讨论】:

  • 你不能这样做return theMessage;,因为theMessage是一个局部变量,而且delay(250)在那里什么也不做。
  • 有几个问题:1)return 语句返回一个'pointer to byte',但声明的返回类型是'byte' 2)在移动内存时不需要第一次延迟到记忆中。 3)第二个延迟将永远不会执行,因为它之前的return语句。 4) 当函数退出时,message[] 数组未定义,因此需要 malloc 一个区域并返回一个指向该 malloc'd 区域的指针。

标签: android c arduino adk


【解决方案1】:

您需要使用动态分配,或者将数组作为参数传递给函数,这在您的情况下是更好的解决方案

void receiveMessage(AndroidAccessory acc, boolean accstates, byte *theMessage){
    if (theMessage == NULL)
        return;
    if(accstates){
        byte rcvmsg[255];
        int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);
        if (len > 0) {
            if (rcvmsg[0] == COMMAND_TEXT) {
                if (rcvmsg[1] == TARGET_DEFAULT){
                byte textLength = rcvmsg[2];
                int textEndIndex = 3 + textLength;
                int i=0;
                    for(int x = 3; x < textEndIndex; x++) {
                        theMessage[i]=rcvmsg[x];
                        i++;
                        delay(250);
                    }
                return;
                }
            }
        }
    }       
}

这样,您将调用将数组传递给它的函数,例如

byte theMessage[255];

receiveMessage(acc, accstates, theMessage);
/* here the message already contains the data you read in the function */

但是你不能返回一个局部变量,因为数据只在变量有效的范围内有效,实际上它在if (rcvmsg[0] == COMMAND_TEXT)块之外是无效的,因为你在那个块本地定义了它。

注意:请阅读Wimmel的评论,或者如果只是文本,可以将最后一个字节设置为'\0',然后将数组用作字符串.

【讨论】:

  • 您可能希望返回收到的消息的长度,以便调用者知道是否收到了某些内容以及收到了多少。
  • 这个行会收到消息 int len = acc.read(rcvmsg, sizeof(rcvmsg), 1);我用这种方法来接收它,所以我不能在轧花之前把它弄碎
【解决方案2】:

就错误而言,您返回的值不正确。

theMessage is a byte array not a byte 

最后的答案也解释了为什么你不能返回局部变量指针

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2021-08-26
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多