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

据我所知,在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.

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...