将Delphi const字符串参数传递到内存管理器边界是否安全?

him*_*elf 7 delphi string parameters const

SUBJ.我想使用字符串而不是PChar,因为这样可以节省很多时间,但如果我这样做的话

procedure SomeExternalProc(s: string); external SOMEDLL_DLL;
Run Code Online (Sandbox Code Playgroud)

然后使用非共享内存管理器在其他项目中实现它:

library SeparateDll;
procedure SomeExternalProc(s: string);
begin
  //a bla bla bla
  //code here code here
end;
Run Code Online (Sandbox Code Playgroud)

我(正式)不保证Delphi不会因任何原因决定更改字符串,修改其引用计数器,复制或唯一它,或其他任何东西.例如

var InternalString: string;

procedure SomeExternalProc(s: string);
begin
  InternalString := s;
end;
Run Code Online (Sandbox Code Playgroud)

Delphi递增refcounter并复制指针,就是这样.我想让Delphi复制数据.将参数声明为"const"会使其安全吗?如果没有,有办法吗?将参数声明为PChar似乎不是解决方案,因为您需要每次都将其强制转换:

procedure SomeExternalProc(s: Pchar); forward;
procedure LocalProc;
var local_s: string;
begin
  SomeExternalProc(local_s); //<<--- incompatible types: 'string' and 'PAnsiChar'
end;
Run Code Online (Sandbox Code Playgroud)

Mas*_*ler 13

这可能会奏效,只要您只使用在相同版本的Delphi中编译的代码中的DLL.已知字符串的内部格式在不同版本之间会发生变化,并且您无法保证它不会再次更改.

如果你想避免在任何地方使用它,请尝试包装函数,如下所示:

procedure SomeExternalProc(s: Pchar); external dllname;
procedure MyExternalProc(s: string); inline;
begin
  SomeExternalProc(PChar(local_s));
end;
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中,你打电话MyExternalProc而不是SomeExternalProc,每个人都很高兴.


gab*_*abr 6

如果应用程序和DLL都是在同一个Delphi版本中编写的,那么只需使用共享内存管理器(这里有更多详细信息).

如果一方用不同的语言编写,除了使用PChar或WideString之外别无其他方式(WideStrings由COM内存管理器管理).

或者你可以编写一个包装函数:

procedure MyExternalProc(const s: string);
begin
  SomeExternalProc(PChar(s));
end;
Run Code Online (Sandbox Code Playgroud)