jos*_*efx 18
Java程序可以使用JNI访问在本机代码中实现的函数(编译为机器代码的任何东西).与面向对象的本机代码接口需要一个java类,它使用jni将方法调用从java转发到本机类的实例.此类是本机类的java对等方.
一个例子:我们在c ++中有print_hello类,我们需要在java程序中使用,为此我们需要在java中定义它的对等体.
本土班
class print_hello{
public:
void do_stuff(){std::cout<<"hello"<<std::endl;}
}
Run Code Online (Sandbox Code Playgroud)
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;}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7843 次 |
| 最近记录: |