- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用我刚刚编写的以下函数将字符串值转换为全局内存句柄,反之亦然。
但是 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/
我想使用我刚刚编写的以下函数将字符串值转换为全局内存句柄,反之亦然。 但是 StrToGlobalHandle() 导致我的测试程序挂起。所以 GlobalHandleToStr() 还无法测试,我也
由于 GlobalAlloc 在 32 位模型中已成为局部的,因此不能使用它以便在 Win32 应用程序之间共享分配的内存。什么函数正在替换 GlobalAlloc 并使用相同的简单性? (就像检索内
在 Windows 中,如何将 GlobalAlloc 替换为 new? 您好,我有这段代码(来自这里:"Reading from a Mailslot")使用 GlobalAlloc 分配内存。 D
我已经在各种链接上搜索过这个,但仍然存在疑问。 我不明白 LocalAlloc vs GlobalAlloc vs malloc vs new 内存分配的区别。 我已经浏览了 MSDN 的这个链接:
我是一名优秀的程序员,十分优秀!