Swig c++ w/ Java loses type on polymorphic callback functions [duplicate]

孤者浪人 提交于 2019-12-04 13:06:41

After digging around on this problem for the weekend I guess this is a "common" problem that Swig has between C++ classes and Java. The issue is called downcasting and is a common problem of directors. Unfortunately the directors don't seem to be able to handle even this simple case. I've tried every combination of director - like below

%feature("director") Callback;
%feature("director") Parent;
%feature("director") Child;

None of that seemed to help at all but doing the following hack worked ok:

class Callback {
public:
    virtual ~Callback() { std::cout << "Callback::~Callback()" << std:: endl; }
    virtual void run(Parent& p) {
        std::cout << "Callback::run1(" << p.getName() << ")\n";
    }

    virtual void run(Child& c) {
        std::cout << "Callback::run2(" << c.getName() << ")\n";
    }
};

Then in the java class for whatever subtype you need the overload irons itself out.

class JavaCallback extends Callback
{
  public void run(Child p)
  {
    out.p("JavaCallback.run("+p.getClass().getSimpleName()+")");
    out.p("p.getName() = "+p.getName());
    super.run(p);
  }
}

Then magically the output works

bash$ java -Djava.library.path=. runme
Adding and calling a normal C++ callback
----------------------------------------
make child
child type class Parent
Callback::run2(5Child)
Callback::~Callback()
Adding and calling a Java callback
------------------------------------
JavaCallback.run(Child)
p.getName() = 5Child
Callback::run2(5Child)
Callback::~Callback()
java exit

There should probably be a better way to do this, but none of the Swig documentation presented me a clear example of how to do this properly. There was some really impressive code in the libsbml library which might help people create downcasting typemaps which fix the problem, but that was proving very complex for little output... Anyway this was simple and easy.

If anyone can figure out an easy (human) solution I'd be interested in hearing about it.

I ran into a blog post today, it specifically is talking about downcasting types in SWIG, C++, C# - anyway, it might be a good direction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!