C++结构struct st
{
int ivalue1;//长度=4
char cvalue2[4];//长度=4
}struct stEx
{
int ivalue1;//4
st stvalue2;//8
}
在C#NET里怎样计算里面存储的长度,并根据这个结构可以反序列化.目前我用的是序列化长度是有问题的.
{
int ivalue1;//长度=4
char cvalue2[4];//长度=4
}struct stEx
{
int ivalue1;//4
st stvalue2;//8
}
在C#NET里怎样计算里面存储的长度,并根据这个结构可以反序列化.目前我用的是序列化长度是有问题的.
用Encoding.Default取出的长度正确.
Marshal.SizeOf取的包大小正确.
string to byte网上查到一个.转换的长度不正确.没折.
代码如下:
unsafe public struct Head
{
public uint dw1;
public uint dw2;
public fixed byte ExCode[8];
}
Head head = new Head();
//byte[] bt = new byte[8];
//bt = Encoding.Default.GetBytes("1");
//fixed (head.ExCode = bt)
//fixed (byte* pbt = bt)
//head.ExCode = pbt;
head.dw1= (uint)IPAddress.HostToNetworkOrder(SendCmd);
head.dw2= (uint)IPAddress.HostToNetworkOrder(SendContent.Length); int hdlen = Marshal.SizeOf(head);
int conlens = Encoding.Default.GetBytes(SendContent).Length;
byte[] contentbuf = Encoding.Default.GetBytes(SendContent);
byte[] line = new byte[hdlen];
for (int i = 0; i < Marshal.SizeOf(head); i++)
{
line[i] = Marshal.ReadByte(head, i);
} sendbuf = new byte[hdlen + conlens];
LinkByte(line, contentbuf, ref sendbuf);//SENDBUF就是要提交出去的数据
//NET反过来除了头有16位长取消.取包体显示字符
byte[] strbuf = new byte[sendbuf.Length - 16];
SubByte(ref strbuf, sendbuf, 16, strbuf.Length);
return Encoding.Default.GetString(strbuf);//NET显示正常//还有一个问题就是FIXED结构里的public fixed byte ExCode[8];数据怎样赋值.
//刚测试结果显示,NET里传汉字过去就会少字...传两个汉字要少一个汉字.传字符就正确
Console.WriteLine(Marshal.SizeOf(new st()).ToString());
如果按NET加长的话,我就怕服务端接收不可识别.
Encoding.Default.GetBytes(SendContent).Length; 长度也应该是正确的.
字节也数据都正确.就是到对方要少字符...为什么?VC和NET的存放BYTE有什么不同吗?
你那个struct 要加上一个属性:
[StructLayout(LayoutKind.Sequential , Pack=1, CharSet=CharSet.Ansi)]