user3788061
user3788061

Reputation: 11

Delphi 2010 Error E2010 Incompatible types: Char' and 'AnsiChar'

I loaded up some code from Delphi and when I compile it inside Delphi 2010 I get an E2010 Incompatible types: 'Char' and 'AnsiChar'.

How do I resolve this error? help please

function TFKirimEmail.ChAnsiToWide(const StrA: AnsiString): WideString;
var
  nLen: integer;
begin
  Result := StrA;
  if Result <> '' then
  begin
    nLen := MultiByteToWideChar(GetACP(), 1, PChar(@StrA[1]), -1, nil, 0);
    SetLength(Result, nLen - 1);
    if nLen > 1 then
      MultiByteToWideChar(GetACP(), 1, PChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1);
  end;
end;

Upvotes: 0

Views: 4845

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595412

In Delphi 2009 and later, (P)Char is an alias for (P)WideChar, whereas it was an alias for (P)AnsiChar in earlier versions. That is why you are getting a compiler error.

The third parameter of MultiByteToWideChar() expects a PAnsiChar in all versions of Delphi. So simply change PChar to PAnsiChar. Which will work fine considering that StrA is AnsiString and not String (which is an alias for UnicodeString in D2009+), so they will match.

That being said, you should be using the CP_ACP constant instead of the GetACP() function, remove the redundant assignment (and conversion) to Result before calling MultiByteToWideChar(), remove unnecessary character indexing, and remove unnecessary null terminator handling:

function TFKirimEmail.ChAnsiToWide(const StrA: AnsiString): WideString;
var
  nLen: integer;
begin
  Result := '';
  nLen := MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PAnsiChar(StrA), Length(StrA), nil, 0);
  if nLen > 0 then
  begin
    SetLength(Result, nLen);
    MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, PAnsiChar(StrA), Length(StrA), PWideChar(Result), nLen);
  end;
end;

With that said, don't use WideString in D2009+ for non-ActiveX work. UnicodeString is more efficient.

function TFKirimEmail.ChAnsiToWide(const StrA: AnsiString): UnicodeString;

Lastly, since you are setting the CodePage to ACP and the dwFlags parameter to MB_PRECOMPOSED (which is the default if no other flags are specified), you could just eliminate all this code and let the RTL handle the conversion for you, since it uses those same settings internally by default:

function TFKirimEmail.ChAnsiToWide(const StrA: AnsiString): WideString;
begin
  Result := WideString(StrA);
end;

Or:

function TFKirimEmail.ChAnsiToWide(const StrA: RawByteString): UnicodeString;
begin
  Result := UnicodeString(StrA);
end;

In which case, your ChAnsiToWide() function becomes redundant and can be eliminated completely.

Upvotes: 3

Related Questions