我本来是使用vc++的,没问题。
现在改为c# .net ,需要使用网络来传送,传送的是一个结构体。
这个结构体在c是如下表示:
struct DataA
{
         unsigned short type;
         unsigned short len
char UserName[32];
unsigned long info1;
};
现在要在c# 中 使用tcpclient给发送出去。
另外UserName 在c#传送时是 string username,如何转换成为
char UserName[32]; ?

解决方案 »

  1.   

    方法一:
    用序列化来做,先把struct变量序列化,然后形成xml数据,接收方接收后反序列化成struct变量。方法二:
    自己来定义byte流格式,即把struct的每个成员分别转成byte,然后组成byte流;接收方接到后,按照格式然后反向形成struct变量。
      

  2.   

    如果采用方法2如果在下列结构中
    struct DataA
    {
             unsigned short type;
             unsigned short len;
    char UserName[32];
    unsigned long info1;
    };
    type=1
    len=36;
    info1=123456;而UserName 应该来自于一个 string username,
    请问该怎么写这个byte 流格式 ?能否告诉我怎么写,我真是新手啊...
    Byte[] DataSend = new Byte[1024] ;
      

  3.   

    unsigned short =〉bytes: 
    Sample code as follows:
    private byte[] ShortToBytes( short nValue )
    {
       byte[] bytShort = new byte[2];
       bytShort[0] = (byte) ( nValue >> 8 );//High 8 bits
       bytShort[1] = (byte) ( nValue & 0x00FF );//Low 8 bits
       return nValue;
    }bytes => short
    private short BytesToShort( byte[] bytData )
    {
        if( bytData == null || bytData.Length != 2 ) throw new Exception( "Invalid parameters" );    short nReturn = 0;
        nReturn = bytData[0];
        nReturn = ( nReturn << 8 );
        nReturn ^= byteData[1];
        return nReturn; 
    }
      

  4.   

    unsigned long数据和上面是同理,不过位数是64位,即8个字节。
    char[32]可以强转成byte[32],一一对应即可。