什么是原生对象? [英] what is a native object?
问题描述
什么是本机对象意味着我发现java具有与本机objets接口的对等类?
what is a native object means i found the that java has peer class to interface with native objets?
推荐答案
Java程序可以使用 JNI 访问以本机代码实现的功能(任何内容)编译成机器代码)。与面向对象的本机代码接口需要一个java类,它使用jni将方法调用从java转发到本机类的实例。这个类是本机类的java对等。
Java programs can use JNI to access to functions implemented in native code (anything compiled to machine code). Interfacing with object oriented native code requires a java class which forwards method calls from java to an instance of the native class using jni. This class is the java peer of the native class.
一个例子:
我们在c ++中有print_hello类,我们需要在java程序中使用它,要做到这一点,我们需要在java中定义它的对等。
An example: We have the print_hello class in c++ which we need to use in a java program, to do this we need to define its peer in 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实现。以下仅实现了上面声明的一个本机方法。
All methods declared native
require a native jni implementation. The following implements only one of the native methods declared above.
//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();
}
这篇关于什么是原生对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!