在中,只是实现了一个Helloworld。
回忆一下JNI的实现步骤:
1.编写native声明的JAVA类;
2.使用javac命令编译所编写的java类;
3.使用Javah生成JNI头文件.h;
4.编写本地方法实现方法;
5.生成动态库;(如果方法实现是cpp写的话就一定要用g++来编译)
6.在java中调用。
下面的一个例子是C\C++与Java之间进行对象的操作。
1.创建Student类
/* * FileName:Student.java * Description:Class Student * */ package pojo; public class Student { private int id; private String name; public Student(){} public Student(int _id,String _name) { this.id=_id; this.name=_name; } public void setId(int _id) { this.id=_id; } public void setName(String _name) { this.name=_name; } public int getId() { return id; } public String getName() { return name; } public String toString() { return "Name:"+name+" id:"+id; } }2.创建主调类
/* * FileName:JniMain.java * Description:Main class * */ package pojo; public class JniMain { static{ System.loadLibrary("studentbean"); } public static native void sayHello(); public native int getId(); public native void setId(int i); public native void setName(String _name); public native Student getStudent(); public static void main(String[] args) { // TODO Auto-generated method stub JniMain test=new JniMain(); test.setId(101); test.setName("Rose"); Student tmp=test.getStudent(); System.out.println("Id:"+tmp.getId()); System.out.println("Name:"+tmp.getName()); test.sayHello(); } }3.编译java,生成.h
sudo javac pojo/JniMain.java pojo/Student.java
javah -classpath . -jni pojo.JniMain4.根据.h文件写函数实现
创建pojo_JniMain.cpp
#include"pojo_JniMain.h" #include5.编译动态库#include using namespace std; int id=1; jobject student; jstring name; JNIEXPORT void JNICALL Java_pojo_JniMain_sayHello (JNIEnv *evn, jclass cla) { printf("shit~\n"); } JNIEXPORT jint JNICALL Java_pojo_JniMain_getId (JNIEnv *evn, jobject thiz) { return id; } JNIEXPORT void JNICALL Java_pojo_JniMain_setId (JNIEnv *evn, jobject thiz, jint ji) { id=ji; } JNIEXPORT void JNICALL Java_pojo_JniMain_setName (JNIEnv *env, jobject thiz, jstring _name) { //name=env->GetStringUTFChars(_name, 0); jclass studentClass = env->FindClass("pojo/Student"); jmethodID studentMethod = env->GetMethodID(studentClass," ","()V"); jfieldID mId = env->GetFieldID(studentClass,"id","I"); jfieldID mstudentName = env->GetFieldID(studentClass,"name","Ljava/lang/String;"); jobject studentObject = env->NewObject(studentClass,studentMethod); env->SetObjectField(studentObject,mstudentName,_name); env->SetIntField(studentObject,mId,id); student = studentObject; } JNIEXPORT jobject JNICALL Java_pojo_JniMain_getStudent (JNIEnv *env, jobject thiz) { return student; }
sudo g++ -shared -I /usr/local/lib/jdk1.6.0_29/include/ -I /usr/local/lib/jdk1.6.0_29/include/linux/ pojo_JniMain.cpp -o libstudentbean.so6.运行
结果如下:
参考: Java JNI由浅入深(包括:Java和C++互传ArrayList泛型对象参数)-http://blog.csdn.net/u_xtian/article/details/6033963