1

I am trying to wrap the following abstract class using the director feature:

Listener.h:

class Listener {
  protected:
  void onEvent() = 0;
}

my interface file looks like this:

module(directors="1") Listener_Java
feature("director") Listener;
%{
#include "Listener.h"
%}
%include "Listener.h"

the resulting method in the generated Java proxy class looks like:

...
protected void onEvent() {
Listener_JavaJNI.Listener_onEvent();
}

what I would like to do is to generate the method as abstract with no body, like this:

protected void onEvent();

Is there any easy way to do this? the reason I want to make the method abstract is to force any derived class to override this method, because if it isn't overrided, when calling this event in other place in my c++ code, an exception arises (because it attempts to invoke pure virtual function that is not implemented)

Or.m
  • 38
  • 6
  • 1
    There is an option for a workaround that I've written before: http://stackoverflow.com/questions/8168517/generating-java-interface-with-swig – Flexo Sep 01 '16 at 16:26
  • Your workaround looks promising, I will try it on sunday. You mentioned in a comment to your answer that "SWIG 3.1 is likely to change this answer substantially", what do you mean? I am willing to use 3.1 as it features the doxygen integration. – Or.m Sep 01 '16 at 17:26

1 Answers1

1

From the SWIG documentation about Directors:

Why isn't the proxy class declared abstract? Why aren't the director upcall methods in the proxy class declared abstract?

Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.) Create an abstract Java subclass that inherits from the director-enabled class instead. Using the previous Foo class example:

public abstract class UserVisibleFoo extends Foo {
  /** Make sure user overrides this method, it's where the upcall
   * happens.
   */
  public abstract void method_upcall(Foo foo_object);

  /// Downcast from Foo to UserVisibleFoo
  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
  {
    try {
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
    }

    catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}

This doesn't prevent the user from creating subclasses derived from Foo, however, UserVisibleFoo provides the safety net that reminds the user to override the method_upcall() method.

vz0
  • 32,345
  • 7
  • 44
  • 77
  • I have read this part in the documentation. "JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.) " - my class won't be using as argument, and the method won't be called from java (the only way it will be called is from the c++ , that's why I need director), that is why I asked for workarounds. Thanks anyway. – Or.m Sep 01 '16 at 16:41