gpt4 book ai didi

delphi - GlobalAlloc 导致我的 Delphi 应用程序挂起?

转载 作者:行者123 更新时间:2023-12-03 18:08:23 25 4
gpt4 key购买 nike

我想使用我刚刚编写的以下函数将字符串值转换为全局内存句柄,反之亦然。

但是 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;

测试代码:

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;

顺便说一句,我想使用这两个函数作为帮助程序在程序之间发送字符串值 - 从进程 A 向进程 B 发送全局句柄,然后进程 B 使用 GlobalHandleToStr() 获取字符串。顺便说一句 2,我知道 WM_COPY 和其他 IPC 方法,这些方法不适合我的情况。

最佳答案

Delphi 2010 中的字符串是 unicode,因此您没有分配正确的缓冲区大小。

替换这一行

Result := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, length(aText) + 1);

有了这个

Result := GlobalAlloc(GMEM_MOVEABLE or GMEM_ZEROINIT, (length(aText) + 1)* SizeOf(Char));

关于delphi - GlobalAlloc 导致我的 Delphi 应用程序挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com