用于包装C ++对象的最佳JNI模式?

时间:2016-01-15 15:29:07

标签: java c++ oop java-native-interface

我正在开发一个Java API,其中许多Java对象实际上是等效C ++对象的包装器。 Java对象创建C ++对象,并在不再需要它们时负责释放它们。我想知道最好的模式,我可以看到两个可能的选择:

  1. 使用静态本机方法调用和最终变量来构造构造函数中的C ++对象以保存本机句柄。

    public abstract class NativeBackedObject1 implements java.lang.AutoCloseable {
    
        protected final long _nativeHandle;
        protected final AtomicBoolean _nativeOwner;
    
        protected NativeBackedObject1(final long nativeHandle) {
            this._nativeHandle = nativeHandle;
            this._nativeOwner = new AtomicBoolean(true);
        }
    
        @Override
        public close() {
            if(_nativeOwner.copareAndSet(true, false)) {
                disposeInternal();
            }
        }
    
        protected abstract void disposeInternal();
    }
    
    public SomeFoo1 extends NativeBackendObject1 {
        public SomeFoo1() {
            super(newFoo());
        }
    
        @Override
        protected final void disposeInternal() {
            //TODO: any local object specific cleanup
            disposeInternal(_nativeHandle);
        }
    
        private native static long newFoo();
        private native disposeInternal(final long nativeHandle);
    }
    
  2. 使用实例本机方法调用和非final变量构造构造函数中的C ++对象以保存本机句柄。

    public abstract class NativeBackedObject2 implements java.lang.AutoCloseable {
        protected long _nativeHandle;
        protected boolean _nativeOwner;
    
        protected NativeBackedObject2() {
            this._nativeHandle = 0;
            this._nativeOwner = true;
        }
    
        @Override
        public void close() {
            synchronized(this) {
                if(_nativeOwner && _nativeHandle != 0) {
                    disposeInternal();
                    _nativeHandle = 0;
                    _nativeOwner = false;
                }
            }
        }
    
        protected abstract void disposeInternal();
    }
    
    public SomeFoo2 extends NativeBackendObject2 {
        public SomeFoo2() {
            super();
            _nativeHandle = newFoo();
        }
    
        @Override
        protected final void disposeInternal() {
            //TODO: any local object specific cleanup
            disposeInternal(_nativeHandle);
        }
    
        private native long newFoo();
        private native disposeInternal(final long nativeHandle);
    }
    
  3. 目前我认为(1)是更好的方法,因为:

    • 一个。这意味着我可以将_nativeHandle设置为不可变(final)。所以我不需要担心并发访问它或意外更改(代码实际上比这些简单的例子更复杂)。
    • 湾由于构造函数,我在设计中已经形式化,NativeBackedObject的任何子类都是其各自本机对象的所有者(由_nativeHandle表示),因为没有它就无法构造。 / LI>

    方法(2)优于(1)或方法(1)有任何问题吗?

    我还可以看到一种替代模式(1),让我们称之为方法(3):

    public abstract class NativeBackedObject3 implements java.lang.AutoCloseable {
        protected final long _nativeHandle;
        protected final AtomicBoolean _nativeOwner;
    
        protected NativeBackedObject3() {
            this._nativeHandle = newInternal();
            this._nativeOwner = new AtomicBoolean(true);
        }
    
        @Override
        public close() {
            if(_nativeOwner.copareAndSet(true, false)) {
                disposeInternal();
            }
        }
    
        protected abstract long newInternal();
        protected abstract void disposeInternal();
    }
    
    public SomeFoo3 extends NativeBackendObject3 {
        public SomeFoo3() {
            super();
        }
    
        @Override
        protected final void disposeInternal() {
            //TODO: any local object specific cleanup
            disposeInternal(_nativeHandle);
        }
    
        @Override
        protected long newInternal() {
            return newFoo();
        };
    
        private native long newFoo();
        private native disposeInternal(final long nativeHandle);
    }
    

    (3)优于(1)的优点是我可以回到默认构造函数,这可以帮助创建测试等模拟。但主要的缺点是我不能再传递额外的参数newFoo()

    也许还有其他方法我错过了?建议欢迎......

2 个答案:

答案 0 :(得分:2)

您是否尝试过可以生成c ++对象的Java包装器的SWIG(http://www.swig.org)?

%typemap(javabody) SWIGTYPE %{
    private long swigCPtr;
    protected boolean swigCMemOwn;

    public $javaclassname(long cPtr, boolean cMemoryOwn) {
        swigCMemOwn = cMemoryOwn;
        swigCPtr = cPtr;
    }

    public static long getCPtr($javaclassname obj) {
       return (obj == null) ? 0 : obj.swigCPtr;
    }
 %}

正如SWIG的文档所述,请考虑简单的测试类:

class Test {
   string str;
public:
  Test() : str("initial") {}
};

它的输出是:

public class Test {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected Test(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

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

  protected void finalize() {
    delete();
  }

  // Call C++ destructor
  public synchronized void delete() {
    if(swigCPtr != 0 && swigCMemOwn) {
      swigCMemOwn = false;
          exampleJNI.delete_Test(swigCPtr);
        }
        swigCPtr = 0;
      }

  // Call C++ constructor
  public Test() {
    this(exampleJNI.new_Test(), true);
  }

}

答案 1 :(得分:1)

根据基准,“通过呼叫,静态”方法确实最有效 https://github.com/adamretter/jni-construction-benchmark 但是JavaCPP基本上使用“By Call,Invoke”(通过缓存jfieldID可以提高BTW的效率。)

我选择这样做的原因是为了生成一个更干净的Java接口文件。用户可以决定手动编写它还是让工具从头文件生成它。无论哪种方式,它最终读取像一些头文件的Java翻译。然而,我们添加到界面越多,它看起来就像C ++一样,并且写入或读取它变得越来越困难。 (这是我不喜欢SWIG的许多事情之一。)

顺便说一句,禁止从JNI修改final变量,这可能是为什么人们可能想要这样做的另一个原因。

当然,仍然可以修改JavaCPP并支持更高效的计算方式,但我们几乎没有任何时间可以节省它尚未证明是一个问题。