Porting unicode to Delphi: Incompatible types: 'Char' and 'AnsiChar' error with Win32 functions such as CharToOEM?

I am trying to convert old Delphi 7 code to Delphi 2010

function AnsiToDOS(S: String): String; begin SetLength(Result, Length(S)); if S <> '' then begin CharToOEM(PChar(S), PChar(Result)); end; end; 

I get the error "Incompatible types: Char" and "AnsiChar" in the line:

CharToOEM (external function of User32) found in

Windows.pas block

Is there any way to rewrite this AnsiToDos function, or do I need to write my own CharToOEM procedure?

+6
source share
2 answers

Unicode Delphi CharToOem displays a version of Unicode CharToOemW , which has the following signature:

 function CharToOem(Source: PWideChar; Dest: PAnsiChar): BOOL; stdcall; 

So you need to provide an ANSI output buffer, but your code provides a Unicode output buffer.

A natural conversion is to switch to the return value of AnsiString . At the same time, the StringToOem function has been renamed to better reflect what it does.

 function StringToOem(const S: String): AnsiString; begin SetLength(Result, Length(S)); if S <> '' then begin CharToOem(PChar(S), PAnsiChar(Result)); end; end; 

An alternative would be to convert to OEM in place, but for this you need to pass the ANSI string and explicitly call the ANSI version of the API call.

 function AnsiStringToOem(const S: AnsiString): AnsiString; begin Result := S; UniqueString(Result); if S <> '' then begin CharToOemA(PAnsiChar(Result), PAnsiChar(Result)); end; end; 

I need to comment that I am surprised to see that the OEM character set is still heavily used today. I thought it went the way of the dinosaurs!

+6
source

The simplest would be (in C ++ Builder):

 typedef AnsiStringT<850> OEMString; AnsiString (or String) aStr = L"my ansi text"; OEMString oStr = aStr; // convert cout << oStr.c_str() << endl; 
-1
source

Source: https://habr.com/ru/post/910621/


All Articles