我定义了一个结构体,结构体中有一个动态数组,需要根据实际情况动态设置其长度,然后通过socket进行发送。
但是每次填写值以后似乎只发送了动态数组的指针地址,并没有发送数组的值。我该如何做呢?type
TStruct = packed record
serialno : array[0..20] of char; //流水号
userNum : byte; //用户数
userIds : array of array[0..20] of char; //用户id
msg : array[0..511] of char; //消息内容
End;
...... var
pkg : TStruct;
i : Integer;
pkgSize : Integer;
begin
setLength(userIds, userList.Count); //创建动态数组
pkgSize := SizeOf(TStruct); //取结构体大小
FillChar(pkg, pkgSize, 0); //对结构填充 #$0 值 with pkg do
begin
StrPCopy(serialno, IntToStr(serial_no));
userNum :=userList.Count; //userList是动态变化的,长度最小为1
//要求每个userId长度都是21字节,不足的用 #$0填充,即字段 userIds 的长度可能是 21,42,63 ...
//而整个数据包的大小也会根据userId的变化而变化
for i :=0 to userList.Count -1 do
StrPCopy(userIds[i], userList[i]);
StrPCopy(msg, 'heart beat!');
end;//with
//通过socket发送该消息体:
Socket.SendBuf(pkg, pkgSize);
//socket发送动作没有错误,但是发送过去的数据中,取到的userIds不正确
end;
但是每次填写值以后似乎只发送了动态数组的指针地址,并没有发送数组的值。我该如何做呢?type
TStruct = packed record
serialno : array[0..20] of char; //流水号
userNum : byte; //用户数
userIds : array of array[0..20] of char; //用户id
msg : array[0..511] of char; //消息内容
End;
...... var
pkg : TStruct;
i : Integer;
pkgSize : Integer;
begin
setLength(userIds, userList.Count); //创建动态数组
pkgSize := SizeOf(TStruct); //取结构体大小
FillChar(pkg, pkgSize, 0); //对结构填充 #$0 值 with pkg do
begin
StrPCopy(serialno, IntToStr(serial_no));
userNum :=userList.Count; //userList是动态变化的,长度最小为1
//要求每个userId长度都是21字节,不足的用 #$0填充,即字段 userIds 的长度可能是 21,42,63 ...
//而整个数据包的大小也会根据userId的变化而变化
for i :=0 to userList.Count -1 do
StrPCopy(userIds[i], userList[i]);
StrPCopy(msg, 'heart beat!');
end;//with
//通过socket发送该消息体:
Socket.SendBuf(pkg, pkgSize);
//socket发送动作没有错误,但是发送过去的数据中,取到的userIds不正确
end;
这样不行,动态数组在结构体中只会存放一个指针。