Delphi的Sharemem - 不需要时 [英] Delphi's Sharemem - When it is not needed
问题描述
我知道,当我在Delphi APP和Delphi DLL之间共享 string
时,我需要添加 Sharemem
应用程序和dll项目源都是use子句中的第一个单元。
但是,如果dll导出仅接受 Pchars
但在一些dll方法里面我使用 string
,我应该使用sharemem吗?让我看看一个示例代码:
procedure ShowMyCustomMessage(aMessage:Pchar);
var
vUselessString:string;
begin
vUselessString:= aMessage;
ShowMessage(vUselessString);
结束
export
ShowMyCustomMessage;
在这个简单而无用的情况下,dll正在接受一个 Pchar
但在导出的方法中,dll创建一个
字符串
var。我应该添加 ShareMem
?
如何 WideString
?通过 WideString
参数需要使用 Sharemem
?
当且仅当在一个模块(即DLL / EXE)中分配内存并在另一个模块中释放内存时,才需要使用Sharemem。这通常发生在您在模块之间通过 string
时。
在给出的示例中,没有必要使用Sharemem。被调用者分配了 PChar
的内存,不被被调用方释放。被调用方的字符串在被调用者中被分配并被释放。
这里是一个需要Sharemem的例子:
函数GetString:string;
begin
结果:='hello';
结束
这里,字符串的内存被分配在被调用者中,但将被调用者释放。 p>
WideString
的情况非常特别。 WideString
是围绕COM BSTR
类型的包装器。它使用共享COM分配器分配和释放。所以它不使用Delphi分配器,你可以安全地通过 WideString
在模块之间,而不使用Sharemem。
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
?
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.
这篇关于Delphi的Sharemem - 不需要时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!