跨内存管理器边界传递Delphi常量字符串参数是否安全? [英] Is it safe to pass Delphi const string params across memory manager boundaries?

查看:129
本文介绍了跨内存管理器边界传递Delphi常量字符串参数是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Subj我想使用字符串而不是PChar,因为这样做很适合我,但是如果我只是这样做,那么我只需要执行

Subj. I'd like to use strings instead of PChar because that spares me much casting, but if I just do

procedure SomeExternalProc(s: string); external SOMEDLL_DLL;

然后在具有非共享内存管理器的其他项目中实现:

and then implement it in some other project with non-shared memory manager:

library SeparateDll;
procedure SomeExternalProc(s: string);
begin
  //a bla bla bla
  //code here code here
end;

我(正式)不保证Delphi不会因为任何原因而改变字符串,修改它引用计数器,重复或唯一的,或者其他的。例如

I have (formally) no guarantee Delphi does not decide for whatever reason to alter the string, modify its reference counter, duplicate or unique it, or whatever else. For example

var InternalString: string;

procedure SomeExternalProc(s: string);
begin
  InternalString := s;
end;

Delphi增加refcounter并复制一个指针,就是这样。我希望Delphi复制数据。将参数声明为const可以使其安全吗?如果没有,有办法吗?声明参数为PChar似乎不是一个解决方案,因为您需要每次转换:

Delphi increments refcounter and copies a pointer, that's it. I'd like Delphi to copy the data. Does declaring the parameter as "const" make it safe for that reason? If not, is there a way to do it? Declaring parameter as PChar doesn't seem to be a solution because you need to cast it every time:

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


推荐答案

这可能会工作,只要你只有使用您的DLL从同一版本的Delphi中编译的代码。已知字符串的内部格式可在版本之间更改,并且您没有正式保证不会再次更改。

That would probably work, as long as you only ever use your DLL from code compiled in the same version of Delphi. The internal format of string has been known to change between releases, and you have no formal guarantee that it won't change again.

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

If you want to avoid having to cast everywhere you use it, try wrapping the function, like this:

procedure SomeExternalProc(s: Pchar); external dllname;
procedure MyExternalProc(s: string); inline;
begin
  SomeExternalProc(PChar(local_s));
end;

然后在代码中,调用 MyExternalProc 而不是 SomeExternalProc ,每个人都开心。

Then in your code, you call MyExternalProc instead of SomeExternalProc, and everyone's happy.

这篇关于跨内存管理器边界传递Delphi常量字符串参数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆