Getting an IStream from an OleVariant

时光毁灭记忆、已成空白 提交于 2019-12-20 02:10:50

问题


I am using Delphi along with WinHTTP to do an HTTP request to download some files from the internet, and I can do the request but I don't know how to get the IStream from the OleVariant that is returned from ResponseStream. I have spent a lot of time googling but I can't figure out how to do it. Here is what I have tried:

var
  req: IWinHTTPRequest;
  instream: IStream;
begin
  req := CoWinHTTPRequest.Create;

  req.Open('GET', 'http://google.com', false);
  req.Send('');

  if req.Status <> 200 then
  begin
    ShowMessage('failure'#10 + req.StatusText);

    FreeAndNil(req);

    Application.Terminate;
  end;

  instream := req.ResponseStream as IStream;

  ShowMessage('success');

  FreeAndNil(instream);
  FreeAndNil(req);

end;

But I get the error [DCC Error] main.pas(45): E2015 Operator not applicable to this operand type (line 45 is instream := req.ResponseStream as IStream;).

How do I scare the IStream out of an OleVariant?


回答1:


Try this

instream := IUnknown(req.ResponseStream) as IStream;

Edit 1 You must not call FreeAndNil on an interface. FreeAndNil can only be passed an object instance. Failure to do so results in an exception. Since interfaces are reference counted anyway you can simply let them go out of scope and they will be cleaned up. So, you need to remove:

  FreeAndNil(instream);
  FreeAndNil(req);

Edit2: A try to explain what is going on

Please feel free to edit or complement if you think this is not accurate or if it can be explained better.

req.ResponseStream is an OleVariant. The as keyword is doing a call to QueryInterface and that is not implemented by OleVariant.

OleVariant has a built in type conversion from OleVariant to IUnknown so you need to first cast the OleVariant to IUnknown and then use the as operator to do a QueryInterface in order to get the IStream interface.

You can not cast a OleVariant directly to a IStream because there is no built in type conversion from OleVariant to IStream.



来源:https://stackoverflow.com/questions/4938601/getting-an-istream-from-an-olevariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!