Link to home
Start Free TrialLog in
Avatar of GiulianoB
GiulianoB

asked on

String to Unicode?

Hi.
I am trying to convert a string/pchar to unicode. The problem is when I call MultiByteToWideString I get a "privilege" error. I am wondering why I can not call this function when it is possible to call them from C++ Compiler. Is there another way to convert to unicode? (UTF8ToUnicode function gives same error)

Thanks!
Avatar of Lee_Nover
Lee_Nover

if you have an UTF8 string then use UTF8Decode()
for ansi strings you can use StringToOleStr()
function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: Integer): Integer;
var
  count: Integer;
  c: Byte;
  wc: Integer;
begin
  if Source = nil then
  begin
    Result := 0;
    Exit;
  end;
  Result := -1;
  count := 0;
  if Dest <> nil then
  begin
  while (Source^ <> #0) and (count < MaxChars) do
  begin
    wc := Integer(Source^);
    Inc(Source);
    if (wc and $80) <> 0 then
    begin
    wc := wc and $3F;
    if (wc and $20) <> 0 then
    begin
      c := Byte(Source^);
      Inc(Source);
      if (c and $C0) <> $80 then  Exit;     // malformed trail byte or out of range char
      wc := (wc shl 6) or (c and $3F);
    end;
    c := Byte(Source^);
    Inc(Source);
    if (c and $C0) <> $80 then Exit;       // malformed trail byte

    Dest[count] := WideChar((wc shl 6) or (c and $3F));
    end
    else
    Dest[count] := WideChar(wc);
    Inc(count);
  end;
  Dest[count] := #0;
  end
  else
  begin
  while Source^ <> #0 do
  begin
    c := Byte(Source^);
    Inc(Source);
    if (c and $80) <> 0 then
    begin
    if (c and $F0) = $F0 then Exit;  // too many bytes for UCS2
    if (c and $40) = 0 then Exit;    // malformed lead byte

    if (Byte(Source^) and $C0) <> $80 then Exit;  // malformed trail byte
    Inc(Source);
    if ((c and $20) <> 0) and ((Byte(Source^) and $C0) <> $80) then Exit; // malformed trail byte
    Inc(Source);
    end;
    Inc(count);
  end;
  end;
  Result := count;
end;
ASKER CERTIFIED SOLUTION
Avatar of andrewjb
andrewjb
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial