2013-04-25 23 views
7

Sapete perché il blocco di codice qui sotto annulla "Non è possibile convertire la variante di tipo (Null) in tipo (OleStr)" su alcuni computer, non tutti, ma 3 computer su dieci generano il messaggio di errore.Impossibile convertire la variante di tipo (Null) nel tipo (OleStr)

enter image description here

function GetWMIstringSW(const WMIClass, WMIProperty:string): string; 

const 
    wbemFlagForwardOnly = $00000020; 

var 
    FWbemObjectSet: OLEVariant; 
    FWbemObject : OLEVariant; 
    oEnum   : IEnumvariant; 
    iValue  : LongWord; 
    LNode   : TTreeNode; 
    LNode2  : TTreeNode; 

begin 
    Result:=''; 
    FWbemObjectSet:= FWMIService.ExecQuery(Format('Select %s from %s',[WMIProperty, WMIClass]),'WQL',wbemFlagForwardOnly); 
    oEnum   := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant; 

    while oEnum.Next(1, FWbemObject, iValue) = 0 do 
    begin 
     if not VarIsNull(FWbemObject.Properties_.Item(WMIProperty).Value) then 
     Result:=FWbemObject.Properties_.Item(WMIProperty).Value; 
     LNode := ClientForm.TreeView1.Items.AddChild(Node, Format('%s',[String(FWbemObject.Name)])); 

     LNode2 := ClientForm.TreeView1.Items.AddChild(LNode, Format('%s',[String(FWbemObject.Version)])); 
     FWbemObject:=Unassigned; 
    end; 

end; 

La funzione viene poi eseguito FormCreate:

GETWMIstringSW('Win32_Product','Name'); 

Grazie mille per il vostro aiuto.

+0

quale variante è nullo? –

+0

Perché non utilizzare i wrapper 'MagWMI' pronti? –

risposta

12

Il codice non riesce quando il valore di una proprietà WMI restituisce null. È possibile risolvere questo problema, controllando se la proprietà ha un valore null prima di eseguire il cast o convertire in una stringa. Per questa attività è possibile utilizzare la funzione VarIsNull o utilizzare semplicemente il metodo VarToStr per convertire in modo sicuro le varianti in stringhe in questo modo.

LNode := ClientForm.TreeView1.Items.AddChild(Node, 
       Format('%s',[VarToStr(FWbemObject.Name)])); 
LNode2 := ClientForm.TreeView1.Items.AddChild(LNode, 
       Format('%s',[VarToStr(FWbemObject.Version)])); 
1

Se si vuole a null varianti da convertire automaticamente stringhe vuote, 0 numeri interi o falsi booleani, impostare NullStrictConvert (System.Variants unità) su true.

2

Per evitare il messaggio di errore fare

NullStrictConvert: = false; // evitare errore di conversione NULL OLE

1

Talvolta, il FWbemObject non è NULL ma un'eccezione è raise: "Can'nt convertire una matrice di variante in OLESTR"

Come Esempio: il BiosVersion (è un array) per risolverlo, provate questo:

per I: = VarArrayLowBound (FWbemObject.BIOSVersion, 1) per VarArrayHighBound (FWbemObject.BIOSVersion, 1) fare L.Add (VarToStr (FWbemObject. BIOSV ersione [i]));

saluti

Zerrouki