我想从C++服务器发送一些数据到C#客户端。我能够发送字符数组。但浮点数组存在一些问题。发送float数组从C++服务器到C#客户端
这是在C++服务器端
float* arr;
arr = new float[12];
//array init...
if((bytecount = send(*csock, (const char*)arr, 12*sizeof(float), 0))==SOCKET_ERROR){
}
的代码,所以是的,我想送过来尺寸12
的float数组这里是为客户端的代码。 (奇怪的是,有没有简单的方法来获得浮出摆在首位流的。我从来没有使用C#之前,也许有更好的东西?)
//get the data in a char array
streamReader.Read(temp, 0, temp.Length);
//**the problem lies right here in receiving the data itself
//now convert the char array to byte array
for (int i = 0; i < (elems*4); i++) //elems = size of the float array
{
byteArray = BitConverter.GetBytes(temp[i]);
byteMain[i] = byteArray[0];
}
//finally convert it to a float array
for (int i = 0; i < elems; i++)
{
float val = BitConverter.ToSingle(byteMain, i * 4);
myarray[i] = val;
}
让我们来看看内存转储两侧和问题将是明确的 -
//c++ bytes corresponding to the first 5 floats in the array
//(2.1 9.9 12.1 94.9 2.1 ...)
66 66 06 40 66 66 1e 41 9a 99 41 41 cd cc bd 42 66 66 06 40
//c# - this is what i get in the byteMain array
66 66 06 40 66 66 1e 41 fd fd 41 41 fd 3d ? 42 66 66 06 40
这里有2个问题关于C#副作用 1)首先它不处理上述0x80的任何东西(127以上)(不兼容的结构) 2)?一些令人难以置信的原因,它降低了一个字节!
,这发生在“临时”就在接收到数据
我一直在试图找出仍然出来的东西,但没有时间。 你知道为什么会发生这种情况吗?我敢肯定我做错了什么... 建议更好的方法?
非常感谢
'StreamReader'被定义为'System.IO.StreamReader()'。是的,我认为'BinaryReader'可能是一个更好的选择。谢谢,让我试试看。 –
sg88
谢谢!!尝试和测试它 - 它的作品 – sg88