2017-07-16 363 views
-2

我想使用MultiByteToWideChar,但我得到'未声明的标识符'。它在哪里宣布?哪个'使用'?如何在delphi中使用MultiByteToWideChar?

我正在使用Embarcadero Delphi XE8。

+0

使用[UnicodeFromLocaleChars](http://docwiki.embarcadero.com/Libraries/XE8/en/System.UnicodeFromLocaleChars)。 – Victoria

回答

0

它在Windows单元中定义;只需在使用条款中添加Windows;

uses 
    Windows; 


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; 
1

这是一个Windows API函数,所以如果你想调用它,你必须使用Winapi.Windows

如果您编写跨平台代码,请改为拨打UnicodeFromLocaleChars

+0

但请注意,在POSIX平台(macOS,iOS,也可能是Android)上,'UnicodeFromLocaleChars'是ssslllooowww。在我的Mobile.AnsiString单元中(当AnsiString在移动编译器中不可用时),我可以将它加速10倍甚至更多。在Windows上,它速度很快,但并不完全正确(MultiByteToWideChar也不是它在内部使用的)。 –