[vtkusers] Translating small python code snippet to c++

Obada Mahdi omahdi at gmx.de
Wed Nov 1 11:19:27 EST 2006


Hi Prename,

the two lines you are quoting just define a function named "Keypress"
with two parameters and instruct the interpreter that the variables
"mpr", "mip" and "surface" are global variables.

The use of VTK observers in Python compared to C++ differs in the way
observers are passed to "AddObserver": In Python, a reference to the
handler function is passed directly, while in C++ a reference to an
instance compatible to vtkCommand is expected. vtkCallbackCommand can
be used in C++ code to have a custom function invoked whenever the
observed event is fired, just like it is the case in your Python
snippet.

On 11/1/06, Prename Surname <bsd.diverse at gmail.com> wrote:
> I have found this codesnippet written in python, but i cannot really
> translate it into C++.
[...]
>  def Keypress(obj, event):
>   global mpr, mip, surface
>   key = obj.GetKeySym()
[...]
>  iren.AddObserver("KeyPressEvent", Keypress)

A C++ version could look something like:
----BEGIN----
// Global variables (I suppose they are simple boolean flags)
int mpr = 0, mip = 0, surface = 0;

void
Keypress(vtkObject* obj, unsigned long event, void* clientdata, void* calldata)
{
  // Safely convert caller object back to vtkRenderWindowInteractor
  vtkRenderWindowInteractor* iren =
vtkRenderWindowInteractor::SafeDownCast(obj);
  char* key = iren->GetKeySym();
  // ...
}

// ...
// `iren' is the instance of vtkRenderWindowInteractor
vtkCallbackCommand* keypressCallback = vtkCallbackCommand::New();

keypressCallback->SetCallback(Keypress);
iren->AddObserver("KeyPressEvent", keypressCallback);
// `AddObserver' increases the reference count of `keypressCallback'.
// By calling `Delete()' here it will be implicitly freed once `iren' is freed.
keypressCallback->Delete();
----END----

Instead of using gloabl variables for "mip", "mpr" and "surface",
other solutions might be more appropriate, depending on the context of
that code snippet.

If those three variables are used exclusively in "Keypress", and there
is at most one such handler present at any given time, the best thing
might be to define them "static" inside "Keypress":

----BEGIN----
void
Keypress(...)
{
  static int mpr = 0, ...
----END----

The most flexible (and "clean") approach is to store any non-local
data used by "Keypress" in a data structure or class instance (like a
controller object) that is then made available to the callback through
the "clientdata" parameter, which can be set up by calling
vtkCallbackCommand::SetClientData().


HTH,

Obada



More information about the vtkusers mailing list