You are not logged in.
Pages: 1
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
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
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
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.
Offline
Pages: 1