pchar 和 pbyte 有什么区别
为什么我无法执行此操作:
var
data:pbyte;
x:int64;
o:pointer;
begin
o:=data+x;
end;
Why can't I perform this operation:
var
data:pbyte;
x:int64;
o:pointer;
begin
o:=data+x;
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PChar 是一个指向 char 的指针,但它得到了编译器的特殊支持,允许指针算术使 Delphi 中类似 C 的字符串操作变得更容易。 PByte 只是一个普通的旧类型指针,编译器没有特别注意允许指针算术。
在 Delphi 2009 中,引入了新的编译器指令 ($POINTERMATH ON/ OFF),它允许您将指针算术的编译器支持添加到您自己的指针类型声明中。
PChar is a pointer to char, but it receives special support from the compiler to allow pointer arithmetic to make C-like string manipulations easier in Delphi. PByte is just a plain old typed pointer, and does not receive any special attention from the compiler to allow pointer arithmetic.
In Delphi 2009, a new compiler directive was introduced ($POINTERMATH ON/OFF) which allows you to add compiler support for pointer arithmetic to your own pointer type declarations.
在旧的 Delphi 版本(D2009 之前)中,
SizeOf(char)
=SizeOf(byte)
,即 8 位。在 D2009 及更高版本中,
char
为 16 位,而byte
仍为 8 位,因此:要允许通过添加值等方式修改指针,您可以使用
$POINTERMATH ON
(在 D2009 及更高版本中提供,请参阅 此处)。另一种方法是遵循以下模式:Edit1 - 请注意(正如在另一个答案的注释中指出的那样),
inc()
和dec()
也可以使用类型化指针;它们将按 SizeOf(TMyType) 递增/递减 PMyType。Edit2 - 为了使您的代码面向未来,您应该考虑 SizeOf(Pointer) 在未来的 64 位 Delphi 版本中可能会发生变化,因此关系
SizeOf(Integer)=SizeOf(Pointer)
将不再持有。为了避免这种情况,最近的 Delphi 版本定义了NativeInt
和NativeUInt
类型,它们是与指针
大小相同的整数。In old Delphi versions (prior to D2009),
SizeOf(char)
=SizeOf(byte)
, i.e., 8-bit.In D2009 and later,
char
is 16-bit whereasbyte
remains 8-bit, so that:To allow modifying pointers by e.g. adding values etc., you can use
$POINTERMATH ON
(available in D2009 and later, see here). The alternative is to follow the pattern:Edit1 -- Note that (as pointed out in comments to another answer), also
inc()
anddec()
work with typed pointers; they will increment/decrement a PMyType by SizeOf(TMyType).Edit2 -- For future-proofing your code, you should consider that SizeOf(Pointer) will probably change in future 64-bit Delphi versions, so that the relationship
SizeOf(Integer)=SizeOf(Pointer)
will no longer hold. To circumvent this, recent Delphi versions define the typesNativeInt
andNativeUInt
, which are integers that have the same size as apointer
.