Re: open save dialog with api

Posted by webmaster Guido on February 17, 2001:

In Reply to: pchar & string posted by idname on February 16, 2001:

: How can I convert a var of type PChar to String??
: I know in good old pascal I could do it like this c:=@s or c:=addr(s), but doesnt seem like working in delphi.
: Can sombody help me out here plz

In the following notes, by "string" we mean "long string". In 32 bit Delphi, "string" in fact is a "long string" ("AnsiString"). The old "Delphi 1 string" only exists for backward compatibility and is now called "short string".

Also, for all the examples, assume the following declarations:

var S, S1, S2: string;
var P, P1, P2: PChar;
var N: integer;

To convert a variable of the type PChar to a string, there are several possibilities:

1. Simply assign the value of a PChar variable to a string variable. The following example copies a null-terminated string into the string variable S:

GetWindowsDirectory(P, 256); // a WinAPI function
S := P;

2. You can mix string values and PChar values in expressions and assignments. For example:

S := 'The Windows directory is ' + P;

3. You can pass PChar values as parameters whe re strings are accepted. Example:

S := LowerCase(P);

4. You can cast a PChar value as a long string. Example:

S := string(P1) + string(P2);

You can also do the reverse, cast a string as a null-terminated string, such as:

// MessageBox is declared in the Windows interface unit
MessageBox(0, PChar(S1), PChar(S2), MB_OK);

In general, you can do this:

P := PChar(S);

But be careful: when you cast a long-string expression to a pointer, the pointer should usually be considered READ-ONLY. Using the pointer to modify the long string gives only correct results under very strict conditions, which would lead us to far to explain them here. In general, DO NOT try something like:

P := PChar(S);
S2 := SomeFunction(S);

Finally, it's useful to know that you can also do the following:

1. Assign a string constant to a PChar. Example:

P := 'DelphiLand';

Now, P points to an area of memory that contains a null-t erminated copy of 'DelphiLand'.
This is equivalent to:

const arrDelphiLa: array[0..10] of Char = 'DelphiLand'#0;
P: PChar;
P := @arrDelphiLa;

2. Pass string constants to functions that take PChar parameters, for example:

P := StrUpper('DelphiLand');

3. Initialize PChar constants with string literals, for example:

const Welcome: PChar = 'Welcome to DelphiLand!';