Recent

Author Topic: [Solved] Problem with using TEncoding on Linux  (Read 2490 times)

drwolf

  • Newbie
  • Posts: 2
[Solved] Problem with using TEncoding on Linux
« on: December 14, 2017, 06:16:33 pm »
I have this example of program:

Code: Pascal  [Select][+][-]
  1. program enctest;
  2.  
  3. uses
  4.   SysUtils, Classes;
  5.  
  6. var
  7.   s: string;
  8.   b: TBytes;
  9.   f: TFileStream;
  10.  
  11. begin
  12.   s := 'zФ';
  13.   b := TEncoding.Convert(TEncoding.UTF8, TEncoding.GetEncoding(1251), BytesOf(s));
  14.  
  15.   f := TFileStream.Create('output.txt', fmOpenWrite);
  16.   f.WriteBuffer(Pointer(b)^, Length(b));
  17.   f.Free;
  18. end.  
  19.  

This program works fine if it is compiled on Windows. If it is compiled on Linux text is not converted to win1251 encoding and is saved to file as UTF-8. Why? This source is saved as UTF-8 text and s variable has UTF-8 encoding. BytesOf retrieves correct bytes from s, but TEncoding.Convert does nothing insted of converting bytes to win1251.

Im using Xubuntu 14.04 and FPC 3.0.4 with Lazarus 1.8, installed from deb pakages.
« Last Edit: December 14, 2017, 08:49:22 pm by drwolf »

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: Problem with using TEncoding on Linux
« Reply #1 on: December 14, 2017, 08:14:41 pm »
Try adding cwstring to your uses section in a conditional define as in the example at the bottom of this page.

drwolf

  • Newbie
  • Posts: 2
Re: Problem with using TEncoding on Linux
« Reply #2 on: December 14, 2017, 08:48:41 pm »
Try adding cwstring to your uses section in a conditional define as in the example at the bottom of this page.

It works! Thak you very much, engkin! Problem is solved.

Remy Lebeau

  • Hero Member
  • *****
  • Posts: 1312
    • Lebeau Software
Re: [Solved] Problem with using TEncoding on Linux
« Reply #3 on: December 18, 2017, 07:08:23 pm »
On a side note, you have a memory leak.  The object returned by TEncoding.GetEncoding() needs to be freed when you are done using it, eg:

Code: [Select]
var
  ...
  Enc: TEncoding:
begin
  ...
  Enc := TEncoding.GetEncoding(1251);
  try
    b := TEncoding.Convert(TEncoding.UTF8, Enc, BytesOf(s));
  finally
    Enc.Free;
  end;
 ...
end. 
Remy Lebeau
Lebeau Software - Owner, Developer
Internet Direct (Indy) - Admin, Developer (Support forum)

Thaddy

  • Hero Member
  • *****
  • Posts: 14201
  • Probably until I exterminate Putin.
Re: [Solved] Problem with using TEncoding on Linux
« Reply #4 on: December 18, 2017, 09:02:15 pm »
You are right.
Specialize a type, not a var.

 

TinyPortal © 2005-2018