Question

I'm attempting to convert a string to a TStream. My code below gives me an "Abstract Error" message on the CopyFrom line. I'm against a brick wall here, any ideas on how to solve this?

procedure StringToStream(const AString: string; out AStream: TStream);
var
  SS: TStringStream;
begin
  SS := TStringStream.Create(AString);
  try
    SS.Position := 0;
    AStream.CopyFrom(SS, SS.Size);  //This is where the "Abstract Error" gets thrown
  finally
    SS.Free;
  end;
end;
Was it helpful?

Solution

AStream is declared as OUT parameter, which means it isn't assigned at the beginning of the procedure and the procedure is responsible to assign a proper value to it.

If I interpret your code correct, you should omit the OUT and make sure AStream is instantiated properly when you call the routine.

Some more code showing the call of StringToStream may give some more clues.

OTHER TIPS

The following procedure should do excactly what your looking for. Please note that your usage of AStream is responsible for freeing the instance that is created in this procedure. It is perfectly fine to return the parent class (in this case tStream) rather than the specific descendant.

procedure StringToStream(const AString: string; out AStream: TStream);
begin
  AStream := TStringStream.Create(AString);
end;

You can also code this as a function:

Function StringToStream(const AString: string): TStream;
begin
  Result := TStringStream.Create(AString);
end;

CopyFrom calls ReadBuffer, which calls Read, and Read is declared abstract. What sort of stream are you passing to AStream? If it doesn't implement Read, you'll get an abstract error there. (And the compiler should give you a warning when you instantiate it.)

Declaring AStream as out looks wrong to me. Try removing the out.

If that doesn't help, here is the function I use:

procedure StringToStream(Stream: TStream;const S: String);
begin
Stream.Write(Pointer(S)^, length(S));
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top