[vtkusers] vtkVariant from wrapped languages

David Thompson dcthomp at sandia.gov
Mon Oct 26 21:54:56 EDT 2009


Hi Jeff (and list),

I saw that you submitted bug #8829 and a uservoice.com request for  
accessing vtkVariant methods from wrapped languages. I ran into this  
problem as well and came up with at least a partial workaround for  
python: the code below should give you read-only access to any  
vtkVariant in a vtkVariantArray.

Just call getVariantValue( array, index) and you'll get back a Python  
ctypes object that behaves like a vtkVariant... it has Valid, Type,  
and Data members. With a vtkTable, you can call GetRow() to get a  
vtkVariantArray for a row and then get the value for the column you're  
interested in. The version below only contains Float, Double, and  
LongLong variants but you could easily add the others by changing the  
VTKVARIANTUNION definition.

	David

#!/bin/env vtkpython
from vtk import *
import math
import re
from vtk.util.numpy_support import *
from ctypes import *

# Define some structures/functions for parsing vtkVariant values
class VTKVARIANTUNION(Union):
   _fields_ = [('Float',c_float),('Double',c_double), 
('LongLong',c_longlong)]

class VTKVARIANT(Structure):
   _fields_ = [('Data',VTKVARIANTUNION), ('Valid',c_ubyte),  
('Type',c_ubyte)]

vtkvarptrre = re.compile( '_([0-9A-Fa-f]+)_void_p' )

def getVariantValue( arr, idx ):
   """Given a vtkVariantArray (arr) and an index (idx) into that array,
return a ctype structure that can be used to access values inside
the idx-th variant.
     """
   qrp = long(vtkvarptrre.match(arr.GetVoidPointer(idx)).group(1),16)
   vv = VTKVARIANT()
   memmove( pointer(vv), qrp, sizeof(VTKVARIANT) )
   return vv

# And here's an example that creates a table and then reads some  
values from it:

table = vtkTable()
llc = vtkLongLongArray()
dbc = vtkDoubleArray()
llc.SetName( 'Index')
dbc.SetName( 'Value' )
llc.SetNumberOfTuples( 3 )
dbc.SetNumberOfTuples( 3 )
llc.SetValue( 0, 38 )
llc.SetValue( 1, 41 )
llc.SetValue( 2, 13 )
dbc.SetValue( 0, 39.4 )
dbc.SetValue( 1, 23.7 )
dbc.SetValue( 2, 99.9 )
table.AddColumn( llc )
table.AddColumn( dbc )
for i in range(3):
   row = table.GetRow( i )
   vval = getVariantValue( row, 0 )
   print '  Valid? %d Type: %d LongLong: %d' % ( vval.Valid,  
vval.Type, vval.Data.LongLong )
   vval = getVariantValue( row, 1 )
   print '  Valid? %d Type: %d Double: %g' % ( vval.Valid, vval.Type,  
vval.Data.Double )






More information about the vtkusers mailing list