stringdelphiunicodedelphi-xe8

how to use MultiByteToWideChar in delphi?


I am trying to use MultiByteToWideChar but i get 'undeclared identifier' . Where is it declared ? which 'uses' ?

I am using Embarcadero Delphi XE8.


Solution

  • The MultiByteToWideChar Windows API function (Win32/Win64) is defined in Delphi or FreePascal in the Windows unit; just add Windows or Winapi.Windows to the uses clause.

    You may wish to use wrapper function written in Delphi to convert RawByteString (or AnsiString) to UnicodeString and vice versa, rather than calling the MultiByteToWideChar directly. Calling it directly may be prone to errors due to incorrect calculation of the lengths of the underlying buffers.

    Please note that Delphi RawByteString or AnsiString have a property to store the Windows code page value, and it is set by the SetCodePage() call in the code below. The code uses explicit types, PAnsiChar vs PWideChar and RawByteString vs UnicodeString to avoid ambiguity.

    uses
      Windows;
    
    const
      CP_UNICODE_LE = 1200;
    
    function StringToWideStringCP(const S: RawByteString; CP: Integer): UnicodeString;
    var
      P: PAnsiChar;
      pw: PWideChar;
      I, J: Integer;
    begin
      Result := '';
      if S = '' then
        Exit;
      if CP = CP_UTF8 then
      begin
        // UTF8
        Result := UTF8ToUnicodeString(S);
        Exit;
      end;
      P := @S[1];
      I := MultiByteToWideChar(CP, 0, P, Length(S), nil, 0);
      if I <= 0 then
        Exit;
      SetLength(Result, I);
      pw := @Result[1];
      J := MultiByteToWideChar(CP, 0, P, Length(S), pw, I);
      if I <> J then
        SetLength(Result, Min(I, J));
    end;
    
    
    function WideStringToStringCP(const w: UnicodeString; CP: Integer)
      : RawByteString;
    var
      P: PWideChar;
      I, J: Integer;
    begin
      Result := '';
      if w = '' then
        Exit;
      case CP of
        CP_UTF8:
          begin
            // UTF8
            Result := UTF8Encode(w);
            Exit;
          end;
        CP_UNICODE_LE:
          begin
            // Unicode codepage
            CP := CP_ACP;
          end;
      end;
    
      P := @w[1];
      I := WideCharToMultibyte(CP, 0, P, Length(w), nil, 0, nil, nil);
      if I <= 0 then
        Exit;
      SetLength(Result, I);
      J := WideCharToMultibyte(CP, 0, P, Length(w), @Result[1], I, nil, nil);
      if I <> J then
        SetLength(Result, Min(I, J));
      SetCodePage(Result, CP, False);
    end;