Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi's Sharemem - When it is not needed

Tags:

memory

dll

delphi

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 in uses clause.

But, if the dll exports function that accept only Pchars but inside some of the dll methods I use strings, should I use sharemem as well? Let me shown a sample code:

procedure ShowMyCustomMessage(aMessage : Pchar);
var
  vUselessString : string;
begin
  vUselessString := aMessage;
  ShowMessage(vUselessString);
end;

exports
  ShowMyCustomMessage;

In that simple and useless case, the dll is accepting a Pchar but inside the exported method the dll creates a string var. Should I add ShareMem as well?

What about WideString? Does passing WideString parameters require the use of Sharemem?

like image 226
Rafael Colucci Avatar asked Dec 07 '11 12:12

Rafael Colucci


1 Answers

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.

like image 159
David Heffernan Avatar answered Nov 11 '22 13:11

David Heffernan