#1 2017-10-01 09:09:00

esmondb
Member
From: London
Registered: 2010-07-20
Posts: 299

Understanding TTextWriter

I'm trying to use TTextWriter with a simple test:

procedure test;
var
  tw: TTextWriter;
begin
  with tw.CreateOwnedStream do
    try

    finally
      Free;
    end;
end;

This gives an Access Violation. but if I declare the TTextWriter globally like:

var
  tw : TTextWriterClass = TTextWriter;

it works. Do TTextWriter vars need to be declared globally or am I missing something?

Offline

#2 2017-10-01 11:39:13

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,131
Website

Re: Understanding TTextWriter

Your code is incorrect, by all Delphi/FPC standards.

CreateOwnedStream is a class constructor, so is expected to be run over a class type (like TTextWriter), not a class instance.
When tw.CreateOwnedStream is run, tw contains some garbage from the stack, so there is an access violation.

In fact, the proper way of writing your code is:

procedure test;
begin
  with TTextWriter.CreateOwnedStream do
    try

    finally
      Free;
    end;
end;

... even if using a with ... do could be source of problems, so a local variable is better for maintainability (and run with the same speed, since "with" creates an hidden local variable):

procedure test;
var
  tw: TTextWriter;
begin
  tw := TTextWriter.CreateOwnedStream;
  try

  finally
    tw.Free;
  end;
end;

It is always better to make everything explicit...

Offline

#3 2017-10-01 12:14:40

esmondb
Member
From: London
Registered: 2010-07-20
Posts: 299

Re: Understanding TTextWriter

Thanks, I should have spotted that.

I got confused by using ObjectToJSON() in syncommons as an example. It seems to use the class constructor in an unusual way.

Offline

#4 2017-10-01 12:51:06

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,131
Website

Re: Understanding TTextWriter

What is confusing is that SynCommons.pas uses a blobal TTextWriterClass instance, to avoid a dependency to TJSONSerializer, which is defined in mORMot.pas.
It is late injection / Dependency Inversion applied at class level. wink

Offline

Board footer

Powered by FluxBB