当AnsiString被转换为PAnsiString时会发生什么? [英] What happens when AnsiString is cast to PAnsiString?
本文介绍了当AnsiString被转换为PAnsiString时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有方法(Delphi 2009):
I have the method (Delphi 2009):
procedure TAnsiStringType.SetData(const Value: TBuffer; IsNull: boolean = False);
begin
if not IsNull then
FValue:= PAnsiString(Value)^;
inherited;
end;
这是一个基类的抽象方法,其中Value:Pointer对应数据,如:
This is an abstract method on the base class, where "Value: Pointer" expects the pointer of the corresponding data, as:
String = PString
AnsiString = PAnsiString
Integer = PInteger
Boolean = PBoolean
所以我试着传递这样的值:
So I try to pass the value like this:
var
S: AnsiString;
begin
S:= 'New AnsiString Buffer';
SetBuffer(PAnsiString(S));
end;
但是从AnsiString到PAnsiString的转换不工作,我可以看到为什么,但我想知道铸造的结果是什么。所以我写了一个简单的测试:
But a cast from AnsiString to PAnsiString does NOT work, I can see why, but I want to know what the result of the casting is. So I wrote a simple test:
var
Buffer: AnsiString;
P1: Pointer;
P2: Pointer;
P3: Pointer;
P4: Pointer;
begin
P1:= PAnsiString(Buffer);
P2:= Addr(Buffer);
P3:= @Buffer;
P4:= Pointer(Buffer);
P5:= PChar(Buffer[1]);
WriteLn('P1: ' + IntToStr(Integer(P1)));
WriteLn('P2: ' + IntToStr(Integer(P2)));
WriteLn('P3: ' + IntToStr(Integer(P3)));
WriteLn('P4: ' + IntToStr(Integer(P4)));
WriteLn('P5: ' + IntToStr(Integer(P5)));
end;
结果是:
P1: 5006500
P2: 1242488
P3: 1242488
P4: 5006500
P5: 67
其中:
- P2 and P3, is the address of Buffer: AnsiString
- P5 is the Char Ord value of Buffer[1] char, in this case "67 = C"
- How about P1 and P4?
P1和P4的意义是什么? b $ b
推荐答案
很好的拼图,但我有解决方案:
Nice puzzle, but I have the solution:
- P2和P3是指向缓冲区的指针的地址
- P1和P4是缓冲区的地址
- P5是第一个元素缓冲区
我在代码中添加了注释:
I have added comment in the code:
var
Buffer: AnsiString;
P1: Pointer;
P2: Pointer;
P3: Pointer;
P4: Pointer;
P5: Pointer;
begin
P1:= PAnsiString(Buffer);
(* A cast from AnsiString to PAnsiString has no real meaning
because both are a pointer to a block of characters ()
P2:= Addr(Buffer);
P3:= @Buffer;
(* Both Addr and @ give the address of a variable. The variable Buffer is
a pointer so we get the address of the pointer, not the value of the
pointer. *)
P4:= Pointer(Buffer);
(* See the remark on P1. Due to the cast both give the same result. *)
P5:= PChar(Buffer[1]);
(* This looks like a pointer to the first element. But the cast changes
it into the character. *)
WriteLn('P1: ' + IntToStr(Integer(P1)));
WriteLn('P2: ' + IntToStr(Integer(P2)));
WriteLn('P3: ' + IntToStr(Integer(P3)));
WriteLn('P4: ' + IntToStr(Integer(P4)));
WriteLn('P5: ' + IntToStr(Integer(P5)));
end;
这篇关于当AnsiString被转换为PAnsiString时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文