什么是本地对象?

10

什么是本地对象?我发现Java有对接本地对象的同级类接口?

2个回答

19

Java程序可以使用JNI来访问在本地代码(编译成机器代码的所有内容)中实现的函数。与面向对象的本地代码进行交互需要一个Java类,该类使用JNI将方法调用从Java转发到本地类的实例。这个类是本地类的Java对等体。

例如:我们有一个C++中的print_hello类,我们需要在Java程序中使用它,为此我们需要定义它在Java中的对等体。

本地类

  class print_hello{
  public:
      void do_stuff(){std::cout<<"hello"<<std::endl;}
  } 

Java 中的 peer 类

  class PrintHello{
    //Address of the native instance (the native object)
    long pointer;

    //ctor. calls native method to create
    //instance of print_hello
    PrintHello(){pointer = newNative();}

    ////////////////////////////
    //This whole class is for the following method
    //which provides access to the functionality 
    //of the native class
    public void doStuff(){do_stuff(pointer);}

    //Calls a jni wrapper for print_hello.do_stuff()
    //has to pass the address of the instance.
    //the native keyword keeps the compiler from 
    //complaining about the missing method body
    private native void do_stuff(long p);

    //
    //Methods for management of native resources.
    //

    //Native instance creation/destruction
    private native long newNative();
    private native deleteNative(long p);

    //Method for manual disposal of native resources
    public void dispose(){deleteNative(pointer);pointer = 0;}
  }

JNI代码(不完整)

所有声明为native的方法都需要一个本地JNI实现。以下仅实现了上面声明的其中一个本地方法。

//the method name is generated by the javah tool
//and is required for jni to identify it.
void JNIEXPORT Java_PrintHello_do_stuff(JNIEnv* e,jobject i, jlong pointer){
    print_hello* printer = (print_hello*)pointer;
    printer->do_stuff();
} 

1

如果Java对象有一些用C语言编写的本地方法,那么它就有一个对等的/本地对象。


你能详细地解释一下吗? - satheesh.droid
更多细节可以查看这些网址:http://www.google.com/search?q=java+peer+class,共有227K个结果。 - Peter Lawrey
这让我们回到了StackOverflow。我们就是摆脱不了它。 - SMUsamaShah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接