Question

Invalid Variant Operation Trying to Access OleVariant

Asked by: davemabe2000

I'm trying to access an olevariant object type using Delphi.  The object is passed through an event handler in the Active X library that I've imported.

Here's what the event handler is defined as in the TLB:

procedure(ASender: TObject; var structQSnap: {??structVTIQSnap}OleVariant) of object;

Ican't seem to set it up so I can properly access the structQSnap object in my event handler.

Also in the TLB, structVTIQSnap is defined as a packed record.

structVTIQSnap = packed record
   bstrSymbol: WideString;
   // other stuff...
end;

Everytime I try to access the bstrSymbol, I get an "Invalid Variant Operation":

procedure TForm1.HandleVTIQuoteSnap(ASender: TObject; var structQSnap: OleVariant);
var
    symbol: WideString;
begin
    symbol := structQSnap.bstrSymbol; // this line causes the exception
end;


How do I access structQSnap to get the symbol string?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-01-26 at 10:49:20ID24084343
Tags

delphi olevariant

Topics

Delphi Programming

,

Windows ATL / WTL / COM Programming

,

Windows OLE Programming

Participating Experts
3
Points
0
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. : Olevariant? How do I access the packed record it repre…
    I am using a VB ocx to connect to an information service. The type library produced the following definitions: procedure GotLogonResponse(var rqn: Smallint; var msg: {??msgLogon} OleVariant); dispid 2; The msgLogon is a packed record msgLogon = packed record ...
  2. pointers, OLEVariant, Arrays of OLEVariant
    Can anybody point me to any documents which clearly explains how to use pointers with OLEVariant and Arrays of OLEVariant. I am being passed parameters of these types from a Server and need to extract the data that is being passed to my program. I am finding it all very confu...
  3. OLEVariant problem
    Hi! I have a ActiveX component, that is giving me some problems. I'll try to explain : The ActiveX after install, was instaled correctly. However, there was another COM that didn't install, but with Project>Import Type Library>Install (after finding the .DLL file...
  4. Olevariant and Event
    How to assign an procedure to an Olevariant? (Olevariant<--(TNotifyEvent or some thing like it))
  5. Error Accessing OleVariant in ActiveX Control
    I have the following declaration from an event in an ActiveX control: procedure TfmTPComm.FileTransfer1Progress(Sender: TObject; const FileName, FileSize, BytesCopied, Percent: OleVariant); I am unable to access any of the constants (...
  6. Array as olevariant
    IN VB I have: Dim aArgs(2) As String aArgs(0) = sFilePath aArgs(1) = "QuoteFileName" aArgs(2) = "N" Test.InvokeMethod("ABC", aArgs). Try to do the same from delphi. The problem is that the second parameter of InvokeMethod is a...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: JosephGloszPosted on 2009-01-26 at 11:06:23ID: 23469677

I think by default, olevariants can't contain structured types.  An OleVariant is a kind of Variant and both are discussed by CodeGear here:

http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/devcommon/varianttypes_xml.html

Look at the 2nd paragraphi in the link above.  The OleVariant is specifically discussed near the end of the article.  Specifically:

"OleVariant can only contain the data types defined as compatible with OLE Automation"

but you may also be able to declare your own specialized (record structure) type of variant according to the article.

 

by: davemabe2000Posted on 2009-01-26 at 11:26:37ID: 23469855

So, do you mean create a type with a record structure that matches how "structVTIQSnap = packed record" is defined and then try to cast the OleVariant as that new type?

 

by: JosephGloszPosted on 2009-01-26 at 11:36:25ID: 23469952

Well, I've only ever used simple (intrinsic) types in parameter variants and olevariants. I don't see how the code in the function HandleVTIQuoteSnap can know to automatically typecast the incoming olevariant to a structVTIQSnap.

If it wasn't an OleVariant, you would get a compile error on this line (instead of a runtime exception):

    symbol := structQSnap.bstrSymbol; // this line causes the exception

If TForm1 can reference the TLB in its uses clause, and if the "structVTIQSnap" is in the interface section of the TLB, then you shouldn't need to redeclare the structure.

Otherwise, yes, declare the structure locally. Either way, as long as the function itself can know what a structVTIQSnap is, the following line might work:

    symbol := (structQSnap as structVTIQSnap).bstrSymbol;

I have doubts about this, but this is all I've got.  :(  Good luck.


 

by: davemabe2000Posted on 2009-01-26 at 11:43:36ID: 23470027

Hmm.  Just tried that and get: [DCC Error] Main.pas(296): E2015 Operator not applicable to this operand type.

Any ideas?  Thanks.

 

by: JosephGloszPosted on 2009-01-26 at 12:13:40ID: 23470337

No, sorry I couldn't help.

 

by: Geert_GruwezPosted on 2009-01-27 at 02:24:05ID: 23474915

just an idea :

type
  structVTIQSnap = packed record
     bstrSymbol: WideString;
     // other stuff...
  end;
 
procedure TForm1.HandleVTIQuoteSnap(ASender: TObject; var structQSnap: OleVariant);
var
  symbol: WideString;
  Temp: structVTIQSnap;
begin
  Temp := structQSnap;
  symbol := temp.bstrSymbol;
end;

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: davemabe2000Posted on 2009-01-27 at 02:38:45ID: 23475010

That gives an error "Incompatible Types: structVTIQSnap and OleVariant.

 

by: Geert_GruwezPosted on 2009-01-27 at 02:39:23ID: 23475014

guess that won't work either, sowwy

 

by: rllibbyPosted on 2009-01-27 at 08:37:06ID: 23478248

I never understood Borland's half implementation of structures in COM...  eg you can define them in the type library editor, but there is no IRecordInfo support in the varaint routines.

So, the problem is this: using Ole automation (IDispatch based), you cannot pass structures as direct params; they must be handled as IRecordInfo interfaces. What you have (I believe) in the OleVariant parameter is actually a variant holding the record data and IRecordInfo interface. To start off with, add the following declarations in your source code (in the form unit, below the form declaration is fine).

---

////////////////////////////////////////////////////////////////////////////////
//   Record type identifier
////////////////////////////////////////////////////////////////////////////////
const
  VT_RECORD               =  36;

////////////////////////////////////////////////////////////////////////////////
//   IRecordInfo UUID
////////////////////////////////////////////////////////////////////////////////
const
  IID_IRecordInfo:        TGUID = '{0000002F-0000-0000-C000-000000000046}';

////////////////////////////////////////////////////////////////////////////////
//   IRecordInfo interface
////////////////////////////////////////////////////////////////////////////////
type
  IRecordInfo             =  interface(IUnknown)
     ['{0000002F-0000-0000-C000-000000000046}']
     function RecordInit(out pvNew): HResult; stdcall;
     function RecordClear(pvExisting: Pointer): HResult; stdcall;
     function RecordCopy(pvExisting: Pointer; out pvNew: Pointer): HResult; stdcall;
     function GetGuid(out pGuid: TGUID): HResult; stdcall;
     function GetName(out pbstrName: POleStr): HResult; stdcall;
     function GetSize(out pcbSize: ULONG): HResult; stdcall;
     function GetTypeInfo(out ppTypeInfo: ITypeInfo): HResult; stdcall;
     function GetField(pvData: Pointer; szFieldName: POleStr; out pvarField: TVariantArg): HResult; stdcall;
     function GetFieldNoCopy(pvData: Pointer; szFieldNamd: POleStr; out pvarField: TVariantArg; out ppvData: Pointer): HResult; stdcall;
     function PutField(wFlags: ULONG; pvData: Pointer; szFieldName: POleStr; pvarField: PVariantArg): HResult; stdcall;
     function PutFieldNoCopy(wFlags: ULONG; pvData: Pointer; szFieldName: POleStr; pvarField: TVariantArg): HResult; stdcall;
     function GetFieldNames(var pcNames: ULONG; rgBstrNames: Pointer): HResult; stdcall;
     function IsMatchingType(pRecordInfo: IRecordInfo): HResult; stdcall;
     function RecordCreate: Pointer; stdcall;
     function RecordCreateCopy(pvSource: Pointer; out ppvDest: Pointer): HResult; stdcall;
     function RecordDestroy(pvRecord: Pointer): HResult; stdcall;
  end;

////////////////////////////////////////////////////////////////////////////////
//   RecordInfo structure
////////////////////////////////////////////////////////////////////////////////
type
  PRecordInfo             =  ^TRecordInfo;
  TRecordInfo             =  packed record
     lpRecord:            Pointer;
     pvRecInfo:           IRecordInfo;
  end;

---

Next, add the following support routines:

---

////////////////////////////////////////////////////////////////////////////////
//   Helper functions
////////////////////////////////////////////////////////////////////////////////
function   OleIsRecordType(V: OleVariant): Boolean;
function   OleGetRecord(V: OleVariant; out RecordInfo: TRecordInfo): HResult;
procedure  OleCleanupRecord(var RecordInfo: TRecordInfo);
function   OleGetRecordField(RecordInfo: TRecordInfo; FieldName: String; out Value: OleVariant): HResult;

---

The implementation for these routines is as follows:

---

function OleIsRecordType(V: OleVariant): Boolean;
var  lpVar:      PVariantArg;
begin

  // Cast as pointer to variant arg
  lpVar:=PVariantArg(@V);

  // Resource protection
  try
     // Check for by ref variant type
     if (lpVar^.vt = (VT_VARIANT or VT_BYREF)) then
     begin
        // Get byref variant pointer
        lpVar:=PVariantArg(lpVar.pvarVal);
     end;
  finally
     // Check for VT_RECORD type
     result:=(lpVar^.vt = VT_RECORD) or (lpVar^.vt = (VT_RECORD or VT_BYREF));
  end;

end;

function OleGetRecord(V: OleVariant; out RecordInfo: TRecordInfo): HResult;
var  lpVar:      PVariantArg;
     lpRecord:   PRecordInfo;
begin

  // Clear pointer
  lpRecord:=nil;

  // Resource protection
  try
     // Cast as pointer to variant arg
     lpVar:=PVariantArg(@V);
     // Check vt type
     case lpVar^.vt of
        // Straight record
        VT_RECORD   :  lpRecord:=PRecordInfo(@lpVar^.bVal);
        // ByRef record
        VT_VARIANT or
        VT_BYREF    :
        begin
           // Get byref variant pointer
           lpVar:=PVariantArg(lpVar.pvarVal);
           // Byref is no longer an option at this level
           if (lpVar.vt = VT_RECORD) then
           begin
              // Get the record
              lpRecord:=PRecordInfo(@lpVar^.bVal);
           end;
        end;
        VT_RECORD or
        VT_BYREF  :
        begin
           // Get pointer to the record struture
           lpRecord:=lpVar.byRef;
        end;
     else
        // Not a record type
        lpRecord:=nil;
     end;
     // Set result record
     if Assigned(lpRecord) then
     begin
        // We need to make sure the ref count is updated
        RecordInfo.pvRecInfo:=lpRecord^.pvRecInfo;
        // Create record pointer copy
        RecordInfo.pvRecInfo.RecordCreateCopy(lpRecord^.lpRecord, RecordInfo.lpRecord);
     end;
  finally
     // Check record pointer
     if Assigned(lpRecord) then
        // Success
        result:=S_OK
     else
        // Return failure
        result:=E_NOINTERFACE;
  end;

end;

function OleGetRecordField(RecordInfo: TRecordInfo; FieldName: String; out Value: OleVariant): HResult;
var  lpwszField:    PWideChar;
begin

  // Init the outbound param
  Value:=Unassigned;

  // Check record structure to ensure we have the interface and pointer to the data
  if (Assigned(RecordInfo.lpRecord) and Assigned(RecordInfo.pvRecInfo)) then
  begin
     // Convert string to wide char
     lpwszField:=StringToOleStr(FieldName);
     // Resource protection
     try
        // Attempt to get the field value
        result:=RecordInfo.pvRecInfo.GetField(RecordInfo.lpRecord, lpwszField, TVariantArg(Value));
     finally
        // Free the allocated string
        SysFreeString(lpwszField);
     end;
  end
  else
     // No pointer / interface
     result:=E_NOINTERFACE;

end;

procedure OleCleanupRecord(var RecordInfo: TRecordInfo);
begin

  // Resource protection
  try
     // Check the interface pointer
     if Assigned(RecordInfo.pvRecInfo) then
     begin
        // Check data pointer
        if Assigned(RecordInfo.lpRecord) then
        begin
           // Destroy our copy of the record
           RecordInfo.pvRecInfo.RecordDestroy(RecordInfo.lpRecord);
        end;
     end;
  finally
     // Release interface
     RecordInfo.pvRecInfo:=nil;
     // Clear data pointer
     RecordInfo.lpRecord:=nil;
  end;

end;

---

The next thing that you want to do is test your structQSnap parameter to ensure that is is indeed holding a recordinfo interface. This can be done with the following check:

---

procedure TForm1.HandleVTIQuoteSnap(ASender: TObject; var structQSnap: OleVariant);
begin

  // Determine if record type
  if OleIsRecordType(structQSnap) then
  begin
     ... // Ok to proceed...
 
---

If the check comes back as true, then continue oniwards with the code below. Otherwise, I have NO idea what the data is being passed as.

To extract the field information from the interface (and record data pointer), you need to extract the interface and record data, and create a new copy of the record data This is done for you in the OleGetRecord routine. You can then use the OleGetRecordField to extract the desired field data from the record. When done, make sure you cleanup the interface pointer and record data by using the OleCleanupRecord.

--- eg ---

procedure TForm1.HandleVTIQuoteSnap(ASender: TObject; var structQSnap: OleVariant);
var  ovSymbol:   OleVariant;
     recInfo:    TRecordInfo;
     szSymbol:   String;
begin

  // Determine if record type
  if OleIsRecordType(structQSnap) then
  begin
     // Get record data
     if (OleGetRecord(structQSnap, recInfo) = S_OK) then
     begin
        // Resource protection
        try
           // Get desired field
           if (OleGetRecordField(recInfo, 'bstrSymbol', ovSymbol) = S_OK) then
           begin
              // Get as string
              szSymbol:=ovSymbol;
              // Display field value
              ShowMessage(szSymbol);
           end;
        finally
           // Cleanup record
           OleCleanupRecord(recInfo);
        end;
     end;
  end;

end;

---

Please note that this was compiled and tested on Delphi 5 with a sample AX object that returned a record structure in an ole variant. Let me know if you have problems compiling, or with any of the PVariantArg casts.

Hope this helps,
Russell



 

by: davemabe2000Posted on 2009-01-27 at 08:58:47ID: 23478527

@rllibby

if OleIsRecordType(structQSnap) then

The above line causes an exception: "Invalid Variant Type"

 

by: rllibbyPosted on 2009-01-27 at 10:04:04ID: 23479235

Its Delphi that is throwing the exception.... most likely in the conversion of the byref (var) to the actual OleVariant. Do me a favor and check the .vt type directly using the following code:

procedure TForm1.HandleVTIQuoteSnap(ASender: TObject; var structQSnap: OleVariant);
var  ovSymbol:   OleVariant;
     recInfo:    TRecordInfo;
     szSymbol:   String;
begin

      ShowMessage(IntToStr(PVariantArg(@structQSnap)^.vt));

Let me know what the integral value is

---

Russell

 

by: davemabe2000Posted on 2009-01-29 at 13:53:54ID: 23503112

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...