Search code examples
delphidelphi-xe6

Hoard Memory Manager


How can I use Hoard Memory Manager in Delphi? I am looking for an alternative to FastMM, which is hopeless for serious multithreaded server applications. I looked at ScaleMM2 but it's not stable in 64 bit.

How can I statically link the Hoard Memory Manager. Since it comes with an OBJ file.


Solution

  • Since everyone FAILED to provide a detailed solution. Here is a solution that actually works.

    1: Open libhoard.cpp 2: Add the following lines to the code.

    extern "C"{
    
    __declspec(dllexport) void* scalable_malloc (size_t size)
    {
        return malloc(size);
    }
    
    __declspec(dllexport) void* scalable_realloc (void* ptr, size_t size)
    {
        return realloc(ptr, size);
    }
    
    __declspec(dllexport) void scalable_free (void* ptr)
    {
        free(ptr);
    }
    
    }
    

    3: Compile with nmake windows

    4: Use it

    unit hoard_mm;
    
    interface
    
    implementation
    
    type
      size_t = Cardinal;
    
    const
      hoardDLL = 'libhoard.dll';
    
    function scalable_malloc(Size: size_t): Pointer; cdecl; external hoardDLL;
    function scalable_realloc(P: Pointer; Size: size_t): Pointer; cdecl; external hoardDLL;
    procedure scalable_free(P: Pointer); cdecl; external hoardDLL;
    
    function GetMem(Size: NativeInt): Pointer; inline;
    begin
      Result := scalable_malloc(size);
    end;
    
    function FreeMem(P: Pointer): Integer; inline;
    begin
      scalable_free(P);
      Result := 0;
    end;
    
    function ReallocMem(P: Pointer; Size: NativeInt): Pointer; inline;
    begin
      Result := scalable_realloc(P, Size);
    end;
    
    function AllocMem(Size: NativeInt): Pointer; inline;
    begin
      Result := GetMem(Size);
      if Assigned(Result) then
      FillChar(Result^, Size, 0);
    end;
    
    function RegisterUnregisterExpectedMemoryLeak(P: Pointer): Boolean; inline;
    begin
      Result := False;
    end;
    
    const
      MemoryManager: TMemoryManagerEx = (
        GetMem: GetMem;
        FreeMem: FreeMem;
        ReallocMem: ReallocMem;
        AllocMem: AllocMem;
        RegisterExpectedMemoryLeak: RegisterUnregisterExpectedMemoryLeak;
        UnregisterExpectedMemoryLeak: RegisterUnregisterExpectedMemoryLeak
      );
    
    initialization
      SetMemoryManager(MemoryManager);
    
    end.