我想在C++服务器和C#客户端之间传输一些数据。我已经成功发送了char数组,但是在发送float数组时遇到了问题。
以下是C++服务器端的代码:
float* arr;
arr = new float[12];
//array init...
if((bytecount = send(*csock, (const char*)arr, 12*sizeof(float), 0))==SOCKET_ERROR){
}
是的,我正在尝试发送一个大小为12的浮点数组。
这是客户端代码。(奇怪的是一开始没有简单的方法从流中获取浮点数。我以前从未使用过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
这里有两个C#方面的问题 - 1)首先,它无法处理0x80(大于127)以上的任何内容(不兼容的结构?) 2)由于某种难以置信的原因,它会掉一个字节!!
而这发生在“temp”接收数据的时候。
我一直在尝试找出解决办法,但还是没有头绪。 您有任何想法吗?我确定我做错了什么... 建议采用更好的方法?
非常感谢
StreamReader
被定义为System.IO.StreamReader(<NetworkStream>)
。是的,我认为BinaryReader
可能是更好的选择。谢谢,让我试一下。 - sg88