A
Amuro
Unregistered / Unconfirmed
GUEST, unregistred user!
主线程要把计算结果发送给子线程。我把结果转换成字符串。用自定义消息发送给子线程。
程序示例如下:
const
MyMsg = WM_USER+1;
type
TmyThread = class(TThread)
private
protected
procedure Execute;
override;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
s:string;
pointer;
begin
s:=GetString();//转换计算结果为字符串
GetMem(P,Length(s)+4);//问题
StrPCopy(p,s);
PostThreadMessage(MyThread.ThreadID,MyMsg,
Length(s)+4,Longint(p));
end;
procedure TMyThread.Execute;
var
s:string;
M:TMsg;
Pointer;
begin
if PeekMessage(M ,0, 0, 0, PM_REMOVE) then
begin
if M.message = MyMsg then
begin
s:=PChar(M.lParam);
p:=ptr(M.lParam);
FreeMem(p,M.wParam);
end;
.........
end
end;
问题:如果去掉GetMem(P,Length(s)+4),那么运行十次会有1,2次接收到错误的字符串,
我这样处理后虽然能收到正确的字符串,但觉得不妥。分配的内存正确释放了?谁有更
好的方法?
程序示例如下:
const
MyMsg = WM_USER+1;
type
TmyThread = class(TThread)
private
protected
procedure Execute;
override;
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
s:string;
pointer;
begin
s:=GetString();//转换计算结果为字符串
GetMem(P,Length(s)+4);//问题
StrPCopy(p,s);
PostThreadMessage(MyThread.ThreadID,MyMsg,
Length(s)+4,Longint(p));
end;
procedure TMyThread.Execute;
var
s:string;
M:TMsg;
Pointer;
begin
if PeekMessage(M ,0, 0, 0, PM_REMOVE) then
begin
if M.message = MyMsg then
begin
s:=PChar(M.lParam);
p:=ptr(M.lParam);
FreeMem(p,M.wParam);
end;
.........
end
end;
问题:如果去掉GetMem(P,Length(s)+4),那么运行十次会有1,2次接收到错误的字符串,
我这样处理后虽然能收到正确的字符串,但觉得不妥。分配的内存正确释放了?谁有更
好的方法?