SWIG JAVA如何使用%interface和纯虚拟方法包装C ++多重继承

伯纳多·弗兰肯费尔德

使用SWIG将大量C ++代码包装到JAVA时遇到问题。

我想做的是包装一个派生类,该类在C ++中扩展了其他2个类,但是其中一个类(在下面的示例中为Base1)应该包装为接口。(以说明Java没有多重继承)。

我已经找到了问题,并创建了一个简单的c ++代码来演示该问题:

namespace Space {
  class Base1 {
      public:
    virtual void Method1() = 0;
   };
  class Base2 {
    public:
    virtual void Method2();
  };
  class Derived : public Base1, public Base2 {
    public:
    virtual void Method1();
  };
}

上面的代码表示我要在JAVA中包装的内容。

当我在上面的示例中运行Swig时,它将创建Base1作为接口(应如此)

public interface Base1 {
  long Base1_GetInterfaceCPtr();
  void Method1();
}

并声明(在JAVA中)扩展Base2并实现Base1(也应实现)的派生类BUT,但它不会在实现接口Base1(在Derived内部的Method1)实现所生成的完整派生Java类的Derived类内部创建Java方法。如下:

public class Derived extends Base2 implements Base1 {
  private transient long swigCPtr;

  protected Derived(long cPtr, boolean cMemoryOwn) {
    super(SOURCEIJNI.Derived_SWIGUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Derived obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        SOURCEIJNI.delete_Derived(swigCPtr);
      }
      swigCPtr = 0;
    }
    super.delete();
  }

  public long Base1_GetInterfaceCPtr() {
    return SOURCEIJNI.Derived_Base1_GetInterfaceCPtr(swigCPtr);
  }

  public Derived() {
    this(SOURCEIJNI.new_Derived(), true);
  }
}

因此,我陷入了SWIG生成类(派生的)的Java编译错误,该类未实现其接口(Base1)的所有方法

我想念什么?我已经阅读了文档,应该可以使用...

我的“ .i”文件:(使用swig 3.0.10)

%module SOURCEI

%include <swiginterface.i>
%interface_impl(Space::Base1);

%{
#include "Source.h"
%}
%include "Source.h"
詹斯·蒙克(Jens Munk)

我正在使用swig 3.0.2,它非常适合我。我没有文件swiginterface.i我的Java安装有些麻烦,因此我尝试使用Python和Ruby。对于这两种语言,我都制作了稍微不同的界面文件。

%module example
%{
  #define SWIG_FILE_WITH_INIT
  #include "Source.h"
%}

%interface_impl(Space::Base1);

%include "Source.h"

我已经配备了默认虚拟析构函数的头文件。

namespace Space {
  class Base1 {
  public:
    virtual void Method1() = 0;
    virtual ~Base1() = default;
   };
  class Base2 {
    public:
    virtual void Method2();
    virtual ~Base2() = default;
  };
  class Derived : public Base1, public Base2 {
    public:
    virtual void Method1();
  };
}

我只是用Java尝试过,但确实在Derived中得到了一个方法

 public void Method1() {
     exampleJNI.Derived_Method1(swigCPtr, this);
 }

我如下编译以上内容

swig -java -c++ Source.i
g++ -std=c++11 -fPIC -c Source.cpp Source_wrap.cxx -I/usr/lib/jvm/java-7-openjdk-amd64/include/
g++ -std=c++11 -fPIC -shared Source.o  Source_wrap.o -o libShared.so

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章