0

我正在做一个套接字程序,在我的服务器与设备连接后,我正试图向他发送消息。但是 send() 函数返回的字节数大于存储在我的数组中的字节数。并且没有发送消息。

这是我的代码:

StartSendingMessages()
{
    int retorno;
    CString TextRetorno;

    HEX_bufferMessage = new CHAR[7]; // there are seven bytes

    // specifies the state
    HEX_bufferMessage[0] = 0xF0;
    HEX_bufferMessage[1] = 0x15;
    HEX_bufferMessage[2] = 0x31;
    HEX_bufferMessage[3] = 0x04;
    HEX_bufferMessage[4] = 0x02; // green
    HEX_bufferMessage[5] = 0x0E; // C1
    HEX_bufferMessage[6] = 0xF7;

    retorno = send(sckSloMo, HEX_bufferMessage, sizeof(HEX_bufferMessage), 0); 

    TextRetorno.Format("%d", retorno); // retorno = 8
    AfxMessageBox("Bytes enviados: " + TextRetorno);

    if (retorno == SOCKET_ERROR)
    {
        AfxMessageBox("Error Send!!");
        return;
    }
    else if(retorno != 0)
    {
        AfxMessageBox("Send() OK !!");
    }
}

有谁知道为什么会这样??

4

4 回答 4

4

你不是这个意思sizeof(HEX_bufferMessage)。的类型HEX_bufferMessage是 [大概] char*char*在您的 [64 位] 系统上 a 的大小是 8 个字节。

而是传递数字,最好使用常量,如果值确实是固定7的,则摆脱动态分配。7

const int BUF_SIZE = 7;
char HEX_bufferMessage[BUF_SIZE];

// ...

retorno = send(sckSloMo, &HEX_bufferMessage[0], BUF_SIZE, 0); 
于 2013-11-04T14:31:35.537 回答
2

HEX_bufferMessage 的类型是指向 CHAR 的指针。您在您的 paltform 中使用等于 8 的 sizeof( HEX_bufferMessage )。

于 2013-11-04T14:31:17.907 回答
0

Assuming you've got

TYPE* myPointer;

then sizeof(myPointer) will give you the size of the pointer (i.e. 4 bytes on a 32 bit system, 8 on a 64 bit system), not the size of the array.

You want to do

const int bufferSize = 7;
HEX_bufferMessage = new CHAR[bufferSize]; 

...

retorno = send(sckSloMo, HEX_bufferMessage, sizeof(CHAR) * bufferSize, 0); 
于 2013-11-04T14:32:35.093 回答
0

It seems you assume that sizeof(HEX_buffer_message) yields the number of elements in HEX_buffer_message. It doesn't. It produces the size of the type of HEX_buffer_message which seems to be a 64 bit pointer yielding 8 rather than 7. There is no way to determine the size of an array allocated with new T[n] from the returned pointer. You'll need to use the n passed somehow.

于 2013-11-04T14:33:10.357 回答