【问题标题】:what is a native object?什么是原生对象?
【发布时间】:2010-12-31 08:19:57
【问题描述】:

什么是原生对象意味着我发现 java 具有与原生对象交互的对等类?

【问题讨论】:

    标签: java terminology


    【解决方案1】:

    Java 程序可以使用JNI 访问以本机代码(编译为机器代码的任何内容)实现的功能。与面向对象的本机代码交互需要一个 java 类,该类将方法调用从 java 转发到使用 jni 的本机类的实例。该类是本机类的 java 对等体。

    一个例子: 我们在 c++ 中有 print_hello 类,我们需要在 java 程序中使用它,为此我们需要在 java 中定义它的对等点。

    原生类

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

    java中的对等类

      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();
    } 
    

    【讨论】:

      【解决方案2】:

      如果 Java 对象有一些用 C 编写的 native 方法,则它具有对等/本地对象。

      【讨论】:

      • 你能详细解释一下吗?
      • 有关更多详细信息,我会查看这些google.com/search?q=java+peer+class 227K 点击。
      • 这让我们回到了stackoverflow。我们就是无法摆脱它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 2018-06-23
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多