大家帮我看看这一个问题是怎么处理的
原来的传输方法是用结构体胡静态数组,可是我想帮它转换成动态数组是要怎么转换?这个是原来的代码
===========================================================
type  //发送包定义
  PTMsgPack = ^TMsgPack;    
  TMsgPack  = packed record   
    CMD : integer;      //包类型                             
    Content: Array[0..5000] of char;   //包内容
  end;  
=============================================================客户端发送===========================================
StrPCopy(MsgPack.Content,Str);
Buffer := RawToBytes(MsgPack, sizeof(MsgPack));
IdTCPClient1.IOHandler.Write(Buffer);
============================================================服务端接收===========================================
AContext.Connection.IOHandler.ReadBytes(Buffer,sizeof(MsgPack));
BytesToRaw(Buffer,MsgPack, sizeof(MsgPack));
S:=string(MsgPack.Content);
========================================================如果帮结构体改成
type  //发送包定义
  PTMsgPack = ^TMsgPack;    
  TMsgPack  = packed record   
    CMD : integer;      //包类型                             
    Content: Array  of char;   //包内容
  end; 这样是要怎么做呢?

解决方案 »

  1.   

    Could be multiple ways to achieve the desired results:1. Add a Size of dynamic array member to your recordtype //发送包定义
      PTMsgPack = ^TMsgPack;  
      TMsgPack = packed record  
      CMD : integer; //包类型  
      CSize : Integer; //Array Size
      Content: Array of char; //包内容
      end;When you call SetLength on Contents, you should set the length to CSize member.  
    2. Another approach could be to use streamsprocedure Send(CMD : Integer) // Just for sample
    var
       stream : TStringStream;
    begin
         stream := TStringStream.Create;
         try
         //Do your text handling here and once done
         IdTCPClient1.WriteInteger(CMD);
         IdTCPClient1.WriteInteger(stream.Size);
         IdTCPClient1.OpenWriteBuffer;
         IdTCPClient1.WriteStream(stream);
         IdTCPClient1.CloseWriteBuffer;
         finally
               FreeAndNil(stream);
         end;
         ......
    end;
    ...
    Hope it helps.//Ali
      

  2.   

    type //发送包定义
      PTMsgPack = ^TMsgPack;  
      TMsgPack = packed record  
      CMD : integer; //包类型  
      CSize : Integer; //Array Size
      Content: Array of char; //包内容
      end;如果用上面的这种方法,后面的发送和接收要怎么写呢?
    我试了好多写法,可是一读地址就出现内存错误,能不能给一个示例呢?
      

  3.   

    你这种情况不建议用record。最好考虑用流(Stream).你收到的内存错误是因为
    Content: Array of char;
    是个指针。这个Content成员用之前你需要分配内存(SetLength 函数)。为了避免内存异常你需要先从Socket上读取Content的大小
    Size=.......
    SetLength(MsgPack.Content,Size);
    AContext.Connection.IOHandler.ReadBytes(Buffer,sizeof(MsgPack));
    为什么不想用Stream的理由是什么?//Ali
      

  4.   

    因为。不会用Stream能不能给个Stream的代码
      

  5.   

    上边不已经给你Stream的实例了吗?看看#1楼回答。//Ali
      

  6.   

    你的问题在Content: Array of char; 的初始化,他的长度在你的结构题里面定义的,你需要在stream里面先读取四个字节的CMD在读取四个字节的CSize,根据CSize初始化你的Content,再将stream内content内容读取到你的结构体content中。读取中注意stream的指针位置