所以我有个折叠式的问题。我有两个PChar变量。我首先分配内存,执行一些操作,为第二个变量分配内存--在这个步骤中,第一个变量包含坏值(我在调试时看到了它)。以下是代码:
procedure TReadThread.Execute;
Var
iRead, temp, i, count : Integer;
header, params : PChar;
begin
try
GetMem(header, 12);
iRead := recv(FSocket, header^, 12, 0);
if (iRead<>12) then
raise Exception.Create('Header recieving problem!');
temp := StrToIntDef(String(copy(header,3,4)),0);
if (temp=0) then
raise Exception.Create('Body receiving problem!');
count := temp*SizeOf(Char);
if (count+12<=16384) then
begin
GetMem(params, count);
iRead := recv(FSocket, params^, count, 0);
if (iRead<>count) then
raise Exception.Create('Cant recieve messsage fully!');
end
else
raise Exception.Create('Bad message size (>16 KB)!');
GetMem(FText, temp*SizeOf(Char)+12);
FText := PChar(String(header) + String(params));
FreeMem(header);
FreeMem(params);
except
on E : Exception do
ShowMessage(E.Message);
end;
end;在线上
iRead := recv(FSocket, params^, count, 0);当我寻找变量头值时--我看到了一些令人惊奇的东西--与我在过程开始时看到的不一样。我怎么才能修好它?
发布于 2011-05-21 20:27:38
我猜想FText是PChar。既然您说您使用的是Delphi2010,那么您应该知道Char实际上是WideChar的同义词,宽2字节。我怀疑你真的想要使用AnsiChar。
最突出的问题是,您为FText分配内存,然后将其与分配给FText的分配一起丢弃。更重要的是,当过程结束时,FText引用的内存将被销毁。
我认为你应该做以下几件事:
将calls.
AnsiString.
AnsiChar,使用GetMem,并使用堆栈分配.也许是这样的:
procedure TReadThread.Execute;
Var
iRead, count: Integer;
header: array [0..12-1] of AnsiChar;
params: array [0..16384-1] of AnsiChar;
begin
try
iRead := recv(FSocket, header, 12, 0);
if (iRead<>12) then
raise Exception.Create('Header receiving problem!');
count := StrToIntDef(Copy(header,3,4),0);
if (count=0) then
raise Exception.Create('Body receiving problem!');
if (count+12<=16384) then
begin
iRead := recv(FSocket, params, count, 0);
if (iRead<>count) then
raise Exception.Create('Cant receive messsage fully!');
end
else
raise Exception.Create('Bad message size (>16 KB)!');
SetLength(FText, 12+count);
Move(header, FText[1], 12);
Move(params, FText[13], count);
except
on E : Exception do
ShowMessage(E.Message);
end;
end;发布于 2011-06-28 08:33:25
就像大卫·赫弗南说的。Char是2字节,pChar指向Delphi2010中的Unicode字符。但是大卫的代码有两个问题
对于答案,您可以使用您的代码通过一个简单的更改。只将标头和params变量定义为PAnsiChar。你可以把其他代码不变。
标题,参数: PAnsiChar;
https://stackoverflow.com/questions/6084097
复制相似问题