【发布时间】:2011-07-24 01:19:47
【问题描述】:
我正在尝试将一些数据从 C++ 服务器发送到 C# 客户端。我能够发送 char 数组。但是浮点数组存在一些问题。
这是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# 方面这里有 2 个问题- 1)首先它不处理高于0x80(高于127)的任何东西(不兼容的结构?) 2) 出于某种令人难以置信的原因,它掉了一个字节!!
这发生在接收数据时的“临时”中
我一直在想办法,但还是一无所获。 您知道为什么会发生这种情况吗?我确定我做错了什么... 有更好方法的建议吗?
非常感谢
【问题讨论】: