Search code examples
delphifastmm

Delphi DLL that is compatible with other programming languages


I want to build a DLL that exports functions that return a string. This DLL should work with other programming languages!! I have found all kind of nasty solutions/hacks to this, best one is to make my function return Pchar then call another function contained in the same DLL ( let's call it ReleaseMemory) to release the memory reserved for PChar.

Anyway, recently I have discovered FastShareMem library. It says it can do exactly what I want WITHOUT calling the ReleaseMemory. On the other side FastMM seems to do the same AS LONG as both the DLL and the application uses FastMM as memory manager. This instantly kill the chance of using FastMM as memory manger for my universal DLL. Right?

====================

FastShareMem (http://www.codexterity.com/fastsharemem.htm), Delphi 7, Windows XP 32 bits, Windows 7 64 bits


Solution

  • You are mixing two different scenarios:

    1. Delphi applications using Delphi DLLs
    2. Any application using Delphi DLLs

    In the first scenario, unless you mix Delphi version or do something weird, the memory manager is the same, and the compiler as well. Thereby there are ways to share the memory manager, and then the compiler is able to handle allocations/deallocations properly. That's the scenario in which both FastMM and FastShareMem works - and only this one.

    In the second scenario, the application and the DLL will use different memory managers, maybe very different ones, and there is usually no way to share one. In such a situation the best approach is never to return a PChar allocated inside the DLL, even if you provide a deallocation function, because you can't be sure what the calling language would do later with your PChar on its own, and if the caller has any chance to call the proper deallocation routine before the compiler/interpreter. COM works somewhat in the way you said, but it enforces memory allocation/deallocation through its own memory manager, thereby it's safe. You can't enforce it with plain DLLs, thereby it is not safe.

    The best approach is let the calling language pass you a buffer large enough, and write your PChar there. Of course you need to have some way to tell the caller what size the buffer should be. That's the way Windows itself works, and there are good reasons why they made this choice.