C++ code fragment converted to Python?

David Gobbi dgobbi at irus.rri.on.ca
Wed Nov 3 10:09:01 EST 1999


Hi Dean,

Moving VTK data arrays to and from python involves a fair bit of
black magic.  More below:

On Wed, 3 Nov 1999, Dean N. Williams wrote:

> Dear Vtk Users,
> 
>     I have a code fragment that I am having troubles converting
>     to Python. I am wondering if anyone has done this. I am on
>     a Linux 5.2 RH PC running Python 1.5.2 and Vtk 2.4.
> 
>     The problem is the last statement. That is, casing the vtkFloatArray
>     in Python. I'm not sure how to do this without getting errors.
> 
> C++ code:
> 
> // create a place for the data
>   vtkScalars *scalars = vtkScalars::New();
>     scalars->SetDataTypeToFloat();
>     scalars->SetNumberOfScalars(num);
>     ((vtkFloatArray*)(scalars->GetData()))->SetArray(data,num,0);
> 
> Python Conversion:
> 
> scalars = vtkScalars()
> scalars.SetDataTypeToFloat()
> scalars.SetNumberOfScalars(num)
> vtkFloatArray(scalars.GetData()).SetArray(data,num,0)  # This statement
>                                                        # doesn't work!

There is no way that the final C++ statement can be converted to python.
Even if there was, you can only pass Python strings to void pointers, not
to any other type of pointer.  Try this instead:

scalars.GetData().SetVoidArray(data,num,1)  # always set save=1 !!

You were pretty close.  There are a couple caveats that you have to
watch out for, though:

1) always set save=1, if VTK tries to release memory that was allocated
   in python sparks will fly

2) similarly, when you pass a string as a void *, garbage collection is
   not done.  It is your responsibility to ensure that the python string
   sticks around as long as VTK needs that memory. 

The whole python string -> C++ void pointer conversion is a hack, though
it is useful enough to justify its existence. 

 - David



-----------------------------------------------------------------------------
This is the private VTK discussion list.  Please keep messages on-topic.
Check the FAQ at: <http://www.automatrix.com/cgi-bin/vtkfaq>
To UNSUBSCRIBE, send message body containing "unsubscribe vtkusers" to
<majordomo at gsao.med.ge.com>.  For help, send message body containing
"info vtkusers" to the same address.     Live long and prosper.
-----------------------------------------------------------------------------




More information about the vtkusers mailing list