Delphi's Sharemem - When it is not needed

柔情痞子 提交于 2019-12-30 08:25:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8414972/delphis-sharemem-when-it-is-not-needed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!