[fpc-devel] Variants and strings

Michael Van Canneyt michael.vancanneyt at wisa.be
Mon Dec 20 15:11:51 CET 2004



On Mon, 20 Dec 2004, Joost van der Sluis wrote:

> Hi all,
>
> I've found a problem in the string-implementation of the variants, but I
> thought I would better discus it first, before I start doing all sort of
> work for nothing.
>
> In variants string-values are stored as PWideChar's. (called vOleStr)
> But if you set a string-value to a variant, it's stored and initialized
> as a WideString. Widestrings are ref-counted, and since it's getting
> casted into a PWideChar, things are going wrong. Example:
>
> var v : variant;
>     s : string;
>
> begin
>   v := 'Hello World';
>   s := v;
>   writeln(s);
>   s := v;
>   writeln(s);
> end;
>
> returns only one 'ello World' or in some cases '   d'. That's because in
> the assignment (s:=v) the memory of the Widestring is already freed
> before it's value is assigned to the string. (A new pwidechar is
> initialised at the same memory-location, wich sets the first character
> to #0, the termination of the newly-initialised pwidechar)
>
> I've fixed this in changing the assignment-part to use a PWideChar
> instead of the Widestring. The problem of that solution is that you have
> to allocate memory for the PWideChar. If you change the value of the
> variant, memory should be re-allocated. And I'm curious if the memory
> will be freed when the variant is freed. Writing all those things would
> mean that you're writing all sorts of code, which is already there for
> Widestrings!

You must be careful with this. The implementation on Linux will be
different than on Windows: On Windows the windows variant routines
are used to manage the variants (because they can be passed to other
processes via COM) and on Linux, FPC specific routines are used.

We should take care that the two remain compatible.

> So I want to suggest to change the string-support in variants form
> PWideChar into Widestrings. This is also more Delphi-compatible.
> According to the Delphi help strings in variants are stored in
> Widestrings...

This is not quite true. (or it may depend on the Delphi version)

"if a variant containing an AnsiString is assigned to an OleVariant,
the AnsiString becomes a WideString."

So this needs some thinking, and some input from the compiler guys.

Michael.




More information about the fpc-devel mailing list