Luiz Americo Pereira Camara wrote:
Marc Weustink wrote:
You are casting a pointer as a string... The way to convert PChar to a
string is to use the function StrPas
Only if you use shortstrings. When using ansistrings you can cast a
PChar in to a string like: String(SomePchar)
With ansistrings you seldom (or never) need StrPas
What about the length that is stored just before the memory location
of ansistrings? Does PChar created with StrAlloc have this field?
It is not really a cast. The compiler adds conversion code.
I'm interested in this since currently i use StrPas to convert from
PChar to AnsiString.
that is not needed.
the following app is valid:
program a;
{$mode objfpc}{$h+}
var
p: PChar;
s: String;
begin
p := 'abcdef';
s := p;
end.
PChars will be "autoconverted" to strings
The use of StrPas is from the shortstring times.
Is this (String(PChar)) faster than StrPas?
lets compale to assembler and comapre:
# [10] s := p;
leal -48(%ebp),%eax
call FPC_ANSISTR_DECR_REF
movl $0,-48(%ebp)
movl U_P$S_P,%eax
call fpc_pchar_to_ansistr
movl %eax,-48(%ebp)
movl -48(%ebp),%eax
call FPC_ANSISTR_INCR_REF
movl $U_P$S_A,%eax
call FPC_ANSISTR_DECR_REF
movl -48(%ebp),%eax
movl %eax,U_P$S_A
# [11] s := StrPas(p);
leal -48(%ebp),%eax
call FPC_ANSISTR_DECR_REF
movl $0,-48(%ebp)
leal -304(%ebp),%edx
movl U_P$S_P,%eax
call FPC_PCHAR_TO_SHORTSTR
leal -304(%ebp),%eax
call fpc_shortstr_to_ansistr
movl %eax,-48(%ebp)
movl -48(%ebp),%eax
call FPC_ANSISTR_INCR_REF
movl $U_P$S_A,%eax
call FPC_ANSISTR_DECR_REF
movl -48(%ebp),%eax
movl %eax,U_P$S_A
You see... with StrPas, the pchar is first converted to a short string.
Is safe that will not change to a simple pointer cast in future?
This will break compatebility.
Does it copy the string content?
Yes, its the same code as assigning directly
# [12] s := String(p);
leal -48(%ebp),%eax
call FPC_ANSISTR_DECR_REF
movl $0,-48(%ebp)
movl U_P$S_P,%eax
call fpc_pchar_to_ansistr
movl %eax,-48(%ebp)
movl -48(%ebp),%eax
call FPC_ANSISTR_INCR_REF
movl $U_P$S_A,%eax
call FPC_ANSISTR_DECR_REF
movl -48(%ebp),%eax
movl %eax,U_P$S_A
Marc
_________________________________________________________________
To unsubscribe: mail [EMAIL PROTECTED] with
"unsubscribe" as the Subject
archives at http://www.lazarus.freepascal.org/mailarchives