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
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.