加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – PChar(”)是否保证是指向#0(不是nil)的指针?

发布时间:2020-12-15 04:03:48 所属栏目:大数据 来源:网络整理
导读:据我所知,在Delphi中,空字符串(AnsiString或WideString)可以用nil指针表示,也可以用指向实际空字符串的指针表示. 通过实验,我已经证明在Delphi XE2(具有特定的编译器设置)中,PChar(”)零.但这是保证,还是可能在未来的版本中更改,或者依赖于某些编译器设置?
据我所知,在Delphi中,空字符串(AnsiString或WideString)可以用nil指针表示,也可以用指向实际空字符串的指针表示.

通过实验,我已经证明在Delphi XE2(具有特定的编译器设置)中,PChar(”)<>零.但这是保证,还是可能在未来的版本中更改,或者依赖于某些编译器设置?

我有信心危机.如果有人能给我一个明确的答案,我将不胜感激.

解决方法

是.从字符串文字到PChar的类型转换永远不会是空指针.从具有相同字符类型的字符串到PChar的类型转换也不会为空. (字符串到PChar,AnsiString到PAnsiChar等)

但是,向PChar输入其他东西的类型可能为null. (指向PChar的指针,指向PWideChar的AnsiString等)

该文档在字符串类型主题的Mixing Delphi Strings and Null-Terminated Strings部分中介绍了这一点:

You can also cast a UnicodeString or AnsiString string as a
null-terminated string. The following rules apply:

  • If S is a UnicodeString,PChar(S) casts S as a null-terminated string; it returns a pointer to the first character in S. Such casts
    are used for the Windows API. For example,if Str1 and Str2 are
    UnicodeString,you could call the Win32 API MessageBox function like
    this: MessageBox(0,PChar(Str1),PChar(Str2),MB_OK);. Use
    PAnsiChar(S) if S is an AnsiString.
  • You can also use Pointer(S) to cast a string to an untyped pointer. But if S is empty,the typecast returns nil.
  • PChar(S) always returns a pointer to a memory block; if S is empty,a pointer to #0 is returned.
  • When you cast a UnicodeString or AnsiString variable to a pointer,the pointer remains valid until the variable is assigned a new value
    or goes out of scope. If you cast any other string expression to a
    pointer,the pointer is valid only within the statement where the
    typecast is performed.
  • When you cast a UnicodeString or AnsiString expression to a pointer,the pointer should usually be considered read-only. You can
    safely use the pointer to modify the string only when all of the
    following conditions are satisfied:
    • The expression cast is a UnicodeString or AnsiString variable.
    • The string is not empty.
    • The string is unique – that is,has a reference count of one. To guarantee that the string is unique,call the SetLength,SetString,or
      UniqueString procedures.
    • The string has not been modified since the typecast was made.
    • The characters modified are all within the string. Be careful not to use an out-of-range index on the pointer.

The same rules apply when mixing WideString values with PWideChar values.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读