CSS   发布时间:2022-04-17  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将float数组从C服务器发送到C#客户端大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将一些数据从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,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变量指向什么(即它的类型是什么?)但我建议你改用 BinaryReader.这样,您可以只读取数据 one float at a time,并且从不打扰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.

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

大佬总结

以上是大佬教程为你收集整理的将float数组从C服务器发送到C#客户端全部内容,希望文章能够帮你解决将float数组从C服务器发送到C#客户端所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。