delphi - 在 HostApp 和 DLL 之间预分配内存

标签 delphi memory dll

我有一个提供解码功能的DLL,如下:

function MyDecode (Source: PChar; SourceLen: Integer; var Dest: PChar; DestLen: Integer): Boolean; stdcall; 

HostApp调用“MyDecode”,并传入Source、SourceLen和Dest参数,DLL返回解码后的Dest和DestLen。 问题是:HostApp 不可能知道解码后的 Dest 长度,因此不知道如何预先分配 Dest 的内存。

我知道可以将“MyDecode”拆分成两个函数:

function GetDecodeLen (Source: PChar; SourceLen: Integer): Integer; stdcall;  // Return the Dest's length
function MyDecodeLen (Source: PChar; SourceLen: Integer; var Dest: PChar): Boolean; stdcall; 

但是,我的解码过程很复杂,如果拆分成两个函数会影响效率。

有没有更好的解决方案?


是的,Alexander,这可能是一个很好的解决方案。 主机应用代码:

//... 
MyDecode(....) 
try 
  // Use or copy Dest data 
finally 
  FreeDecodeResult(...) 
end;

DLL 代码:

function MyDecode(...): Boolean;
begin
  // time-consuming calculate

  // Allocate memory
  GetMem(Dest, Size);   
  // or New()?
  // or HeapAlloc()?
end;

procedure FreeDecodeResult(Dest: PChar);
begin
  FreeMem(Dest);
  // or Dispose(Dest); ?
  // or HeapFree(Dest); ?
end;

也许我应该将 Dest 的类型更改为指针。

哪种分配内存更好? GetMem/New 还是 HeapAlloc?

最佳答案

您可以通过其他方式将“MyDecode”拆分为两个例程:

function  MyDecode(Source: PChar; SourceLen: Integer; out Dest: PChar; out DestSize: Integer): Boolean; stdcall;
procedure FreeDecodeResult(Dest: PChar); stdcall;

即- 您在 MyDecode 中分配内存,而不是要求调用者这样做。

关于delphi - 在 HostApp 和 DLL 之间预分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2621127/

相关文章:

windows - 在 Delphi 2K9 中运行时禁用和启用组件。奇怪的问题

delphi - TValue.AsType <T>与Delphi中的枚举类型

c - 如何创建结构体c的动态矩阵?

c# - 从 C# 中列出非 .NET DLL 函数

c# - 如何防止类看到 DLL 文件

Python、ctypes、DLL 和 PCOMM 仿真。如何预分配变量?

delphi - 释放 TStringlist 作为函数结果?

delphi - 防止接口(interface)传递的对象被破坏

android - 在 Android 上组合位图

javascript - Internet Explorer 相当于 window.performance.memory?