R – Using delphi application’s memory manager in a delphi DLL (without recompiling the application)

delphidllmemory-leaksmemory-management

I need to write a DLL (using Delphi) which is dynamically loaded into delphi applications and makes RTTI queries (typical operation is to obtain string values for control properties).
The classic problem is that passing strings (and objects) between application and DLL is problematic due to different memory managers used in both (this might lead to memory issues, e.g. DLL's memory manager would try to free the memory allocated by Application's memory manager).

Is there a way to set DLL's memory manager to application's memory manager in a way that would not depend on delphi version? Any thoughts?

October 2010 edit:

Since interest to this topic is almost lost – I'll describe the (quite poor) solution which I ended up with so that others would understand why I didn't accept any of the proposed answers.

So a hacky way to perform something like this would be to find RVA of MemoryManager structure (refer to implementation part of System.pas) and hardcode in the DLL. This way, DLL would be able to set its private memory manager to be the same as that of the application it is being loaded into. It works with some limitations and issues; anyway – it is very Delphi compiler & linker options dependent.

Though it is not an answer I was searching for – I do not expect anything better than this.

Best Answer

Use the same memory manager for your application and your DLLs.

For recent version of Delphi that includes the new FastMM memory manager, use SimpleShareMem as the 1st unit in both your application and the DLL projects.

Or download the full FastMM4 from SourceForge, set the Flags in FastMM4Options.Inc (ShareMM, ShareMMIfLibrary, AttemptToUseSharedMM) and put FastMM4 as the 1st unit in both the application and the DLLs projects.

Related Topic