string 字符串到 TStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1082559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:28:39  来源:igfitidea点击:

String to TStream

delphistringtstream

提问by Greg Bishop

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

我正在尝试将字符串转换为 TStream。我下面的代码在CopyFrom行上给了我一个“抽象错误”消息。我在这里靠墙,关于如何解决这个问题的任何想法?

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;

回答by Uwe Raabe

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.

AStream 被声明为 OUT 参数,这意味着它不是在过程开始时分配的,过程负责为其分配适当的值。

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

如果我正确解释您的代码,您应该省略 OUT 并确保在调用例程时正确实例化 AStream。

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

显示 StringToStream 调用的更多代码可能会提供更多线索。

回答by skamradt

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.

以下过程应该完全符合您的要求。请注意,您对 AStream 的使用负责释放在此过程中创建的实例。返回父类(在本例中为 tStream)而不是特定的后代是完全可以的。

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;

回答by Mason Wheeler

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.)

CopyFrom 调用 ReadBuffer,后者调用 Read,Read 被声明为抽象的。你传递给 AStream 的流是什么类型的?如果它没有实现 Read,你会在那里得到一个抽象错误。(当你实例化它时,编译器应该给你一个警告。)

回答by Mike Sutton

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

将 AStream 声明为 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;