Stefan
Stefan

Reputation: 29

Delphi XE3: Convert WideChar array to Unicode string HOWTO?

I've done some research here regarding the problem given above and come up with the following code:

VarStr = array of WideChar;

function ArrayToString(const a: VarStr): UnicodeString;
begin
  if Length(a) > 0 then
    begin
      ShowMessage ('Länge des übergebenen Strings: ' + IntToStr(Length(a)));
      SetString(Result, PWideChar(@a[0]), Length(a) div 2)
    end
  else
    Result := '';
end;

ShowMessage displays the correct number of characters in a given array, but the result of the function is always an empty string.

Your ideas please?

Upvotes: 1

Views: 2214

Answers (2)

Ari0nhh
Ari0nhh

Reputation: 5920

Result:= Trim(string(a));

UPDATE: As colleagues graciously pointed in comments, this is a wrong answer! It works only because internal string and dynamic array implementation are pretty similar and there is no guarantee that such code would work in the future compilator versions. The correct way to DynArray->String conversion is described in the David answer. I would not delete my answer to preserve comments, in my opinion their worth is much greater..

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612963

You are passing the wrong length value. You only ask for half of the characters. Fix your code like this:

function ArrayToString(const a: VarStr): string;
begin
  SetString(Result, PWideChar(a), Length(a));
end;

However, you also report that your function returns an empty string. The most likely cause for that is that you are passing invalid input to the function. Consider this program:

{$APPTYPE CONSOLE}

type
  VarStr = array of WideChar;

function ArrayToStringBroken(const a: VarStr): UnicodeString;
begin
  SetString(Result, PWideChar(@a[0]), Length(a) div 2);
end;

function ArrayToStringSetString(const a: VarStr): UnicodeString;
begin
  SetString(Result, PWideChar(a), Length(a));
end;

var
  a: VarStr;

begin
  a := VarStr.Create('a', 'b', 'c', 'd');
  Writeln(ArrayToStringBroken(a));
  Writeln(ArrayToStringSetString(a));
end.

The output is:

ab
abcd

So as well as the problem with the code in your question, you would seem to have problems with the code that is not in your question.

Perhaps when you said:

The result of the function is always an empty string.

You actually meant that no text is displayed when you pass the returned value to ShowMessage. That's a completely different thing altogether. As @bummi points out in comments, ShowMessage will truncate its input at the first null-terminator that is encountered. Use proper debugging tools to inspect the contents of variables.

Upvotes: 6

Related Questions