Cast object as OleVariant in Delphi

旧巷老猫 提交于 2019-12-07 17:20:24

问题


Is there a way to pass a wrap and unwrap a TObject descendent in an OleVariant? I am trying to pass a TObject across automation objects. I know it's not a good idea but I don't have a good alternative.

The object is to be passed between objects from the same automation dll, if that makes any difference.

Something like this:

function GetMyObjAsVariant;
var
  MyObj: TMyObj;
begin
  MyObj := TMyObj.Create;
  result := OleVariant(MyObj);
end;

Which would be used by a client as

var
  MyObj: TMyObj;
begin
  MyObj := GetMyObjAsVariant as TMyObj;
end;

This fails to compile, returning

E2015 Operator not applicable to this operand type.

回答1:


If you absolutely, really want to, and you know for sure both objects are in the same process, you can cast any TObject to an Integer and then back to an TObject:

function GetMyObjAsVariant;
var
  MyObj: TMyObj;
begin
  MyObj := TMyObj.Create;
  result := OleVariant(Integer(MyObj));
end;

and then:

var
  anInt: Integer;
  MyObj: TMyObj;
begin
  anInt := GetMyObjAsVariant;
  MyObj := TMyObj(anInt);
end;



回答2:


You could write and register a custom Variant type; have a look at TSQLTimeStampVariantType for an example.

An alternative would be to write an automation wrapper for your class. The dual dispinterface automatically supports late binding through IDispatch which is supported by OleVariant.




回答3:


Let your object implement an interface and pass the interface.

function GetMyObjAsVariant: OleVariant;
var
  MyObj: IMyObj;
begin
  MyObj := TMyObj.Create;
  result := MyObj;
end;

var
  MyObj: IMyObj;
begin
  MyObj := GetMyObjAsVariant as IMyObj;
end;

I won't guarantee this works, you should go with TOndrej's suggestion and make an automation wrapper for your class. It shouldn't be to hard if you know your way around.



来源:https://stackoverflow.com/questions/2771551/cast-object-as-olevariant-in-delphi

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