-1

我正在使用 raspberry Pi 和 Scratch 进行一个项目。我需要将远程传感器协议与 C++ 一起使用。我尝试过移植 Python 代码,但我无法让 C++ 返回空值。

原始 Python 代码如下所示:

import socket
from array import array

HOST = '192.168.1.101'
PORT = 42001

scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratchSock.connect((HOST, PORT))

def sendCMD(cmd):
    n = len(cmd)
    a = array('c')
    a.append(chr((n >> 24) & 0xFF))
    a.append(chr((n >> 16) & 0xFF))
    a.append(chr((n >>  8) & 0xFF))
    a.append(chr(n & 0xFF))
    scratchSock.send(a.tostring() + cmd)

sendCMD('sensor-update "dave" 201')

我在 C++ 中的尝试如下所示:

char* scratchencode(string cmd)
{
    int cmdlength;

    cmdlength = cmd.length();
    char* combind = new char[20];
    const char * sCmd = cmd.c_str();
    char append[]={(cmdlength >> 24) & 0xFF, (cmdlength >> 16) & 0xFF, (cmdlength >> 8) & 0xFF, (cmdlength & 0xFF)};
    strcpy(combind,append);
    strcpy(combind,sCmd);
    return combind;
}

需要说它不起作用,任何人都可以帮助移植代码,我试图在http://wiki.scratch.mit.edu/wiki/Remote_Sensors_Protocol上模仿 python 代码和原始文件,但没有成功。

克里斯

4

1 回答 1

0

我已经解决了这个问题,谢谢 Paweł Stawarz。您的建议正是我所需要的,我将整个函数转换为使用字符串,并且它第一次起作用。

代码如下:

string scratchencode(string cmd)
{
    int cmdlength; // holds the length of cmd
    string combind; // used to store the concatenated Packet
    string mgsSize; // used to store Message size

    cmdlength = cmd.length(); // length of CMD

    //convert intiger to a  4 byte 32-bit big-Endian number, using bit shifting.
    mgsSize = (cmdlength >> 24);
    mgsSize += (cmdlength >> 16);
    mgsSize += (cmdlength >> 8);
    mgsSize += cmdlength;

    combind = mgsSize + cmd; // concatenate mgsSize and cmd producing a structure of  [size][size][size][size][string CMD (size bytes long)]
    return combind; // return the string
}
于 2014-03-10T19:24:41.843 回答