2

我试图从 dll 函数返回我自己的对象(从 TCollection 派生)。我使用了 FastMemoryManager,但没有成功......所以我尝试返回一些对象的动态数组。
dll函数中当然设置的数组的长度。它工作得很好,但分配的内存没有被释放。
(我用 Windows tarsk manager 测量)。有没有可能如何释放动态数组?调用dll函数的过程在线程中,最后我如下:

for i := 0 to length(MyObjectArray) - 1 do begin
  if MyObjectArray[i] <> nil then
     MyObjectArray[i].Free;
end;
Setlength(MyObjectArray, 0);
MyObjectArray := nil;

如果我使用而不是Setlength(MyObjectArray, 0) 和 MyObjectArray := nil,
则会引发 FreeAndNil(MyObjectArray) 异常。

有什么建议吗?

4

1 回答 1

6

Is ShareMem the first unit in all Delphi DLL and EXE project files? FastMM is already the RTL's memory manager for the past few releases of Delphi.

I would recommend not sharing objects at all between DLLs and EXEs; it's just a recipe for pain. Use packages instead.

If you must use DLLs, I'd advise adopting the usual WinAPI conventions: stdcall calling convention, only using C-compatible data types (integers, floats, pointers, records that have no fields of managed types like strings, arrays or interfaces). Have the DLL do no allocation of memory that the EXE is responsible for freeing. Instead, let the EXE allocate and pass the DLL the memory; alternatively, encapsulate allocations into logical handles, and export functions that dispose of the memory from the DLL, along the lines of e.g. how the CloseHandle WinAPI function works.

于 2010-09-14T12:03:28.723 回答