将float数组从C++服务器发送到C#客户端

sg8*_*g88 7 c# c++ sockets

我正在尝试将一些数据从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){
}
Run Code Online (Sandbox Code Playgroud)

所以是的,我正在尝试发送一个大小为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;
}
Run Code Online (Sandbox Code Playgroud)

让我们看看双方的内存转储问题将会很清楚 -

//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
Run Code Online (Sandbox Code Playgroud)

这里有2个问题在c#侧 - 1)首先它不处理0x80以上的任何东西(127以上)(不兼容的结构?)2)由于一些令人难以置信的原因它丢了一个字节!!

这在接收数据时正好在'temp'中发生

我一直试图找出一些东西,但没有任何东西.你知道为什么会这样吗?我确定我做错了什么...建议采取更好的方法?

非常感谢

Isa*_*avo 5

从你的代码中不清楚streamReader变量指向的是什么(即它的类型是什么?)但我建议你改用BinaryReader.这样,您可以一次只读取一个浮点数据,并且根本不会打扰byte[]数组:

var reader = new BinaryReader(/* put source stream here */)
var myFloat = reader.ReadSingle();
// do stuff with myFloat...
// then you can read another
myFloat = reader.ReadSingle();
// etc.
Run Code Online (Sandbox Code Playgroud)

不同的读者对数据做了不同的事情.例如,文本阅读器(和流阅读器)将假设所有文本都是特定编码(如UTF-8),并且可能以您不期望的方式解释数据.BinaryReader不会这样做,因为它旨在让您准确指定要从流中读取的数据类型.