Edw*_*Yip 2 delphi delphi-2010
我想使用我刚刚编写的以下函数将字符串值转换为全局内存句柄,反之亦然.
但是StrToGlobalHandle()导致我的测试程序挂起.所以GlobalHandleToStr()是不可测试的,我也想知道我的代码是否合乎逻辑.
function StrToGlobalHandle(const aText: string): HGLOBAL;
var
ptr: PChar;
begin
Result := 0;
if aText <> '' then
begin
Result := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, length(aText) + 1);
if Result <> 0 then
begin
ptr := GlobalLock(Result);
if Assigned(ptr) then
begin
StrCopy(ptr, PChar(aText));
GlobalUnlock(Result);
end
end;
end;
end;
function GlobalHandleToStr(const aHandle: HGLOBAL): string;
var
ptrSrc: PChar;
begin
ptrSrc := GlobalLock(aHandle);
if Assigned(ptrSrc) then
begin
SetLength(Result, Length(ptrSrc));
StrCopy(PChar(Result), ptrSrc);
GlobalUnlock(aHandle);
end
end;
Run Code Online (Sandbox Code Playgroud)
测试代码:
procedure TForm3.Button1Click(Sender: TObject);
var
h: HGLOBAL;
s: string;
s2: string;
begin
s := 'this is a test string';
h := StrToGlobalHandle(s);
s2 := GlobalHandleToStr(h);
ShowMessage(s2);
GlobalFree(h);
end;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我想使用这两个函数作为帮助程序在程序之间发送字符串值 - 从进程A发送一个全局句柄到进程B,进程B使用它来获取字符串GlobalHandleToStr().BTW 2,我知道WM_COPY和其他IPC方法,那些不适合我的情况.
Delphi 2010中的字符串是unicode,因此您没有分配适当的缓冲区大小.
替换这一行
Result := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, length(aText) + 1);
Run Code Online (Sandbox Code Playgroud)
有了这个
Result := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, (length(aText) + 1)* SizeOf(Char));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
998 次 |
| 最近记录: |