Delphi's Sharemem - When it is not needed

前端 未结 1 1919
长情又很酷
长情又很酷 2021-01-12 03:05

I know that when I share strings between a Delphi APP and a Delphi DLL I need to add Sharemem in both app and dll project source as the first unit

相关标签:
1条回答
  • 2021-01-12 03:31

    You need to use Sharemem if and only if memory is allocated in one module (i.e. DLL/EXE) and deallocated in a different module. This commonly happens when you are working passing string between modules.

    In the example you give, there is no need to use Sharemem. The memory for the PChar is allocated by the called and is not deallocated by the callee. The string in the callee is allocated and deallocated in the callee.

    Here's an example where you would need Sharemem:

    function GetString: string;
    begin
      Result := 'hello';
    end;
    

    Here the memory for the string is allocated in the callee but will be deallocated by the caller.

    The case of a WideString is quite special. The WideString is a wrapper around the COM BSTR type. It allocates and deallocates using the shared COM allocator. So it does not use the Delphi allocator and you are safe to pass WideString between modules without using Sharemem.

    0 讨论(0)
提交回复
热议问题