1.首先创建HelloWorld.Java文件:
- class Person {
- public String name;
- public int age;
- public boolean student;
- Person(String name, int age, boolean student){
- this.name = name;
- this.age = age;
- this.student = student;
- }
- public String getName()
- {
- return this.name;
- }
- public void setName(String name){
- this.name = name;
- }
- public int getAge(){
- return this.age;
- }
- public void setAge(int age){
- this.age = age;
- }
- public boolean getStudent(){
- return this.student;
- }
- public void setStudent(boolean student){
- this.student = student;
- }
- }
- public class HelloWorld {
- public native void displayHelloWorld();
- public native void displayPerson(Person p);
- static{
- System.loadLibrary("hello");
- }
- public static void main(String[] args){
- new HelloWorld().displayHelloWorld();
- Person p = new Person("hc", 19, true);
- p.setAge(23);
- new HelloWorld().displayPerson(p);
- }
- }
2.在命令行中编译java文件:
javac HelloWorld.java
编译生成.h文件:
javah HelloWorld
生成HelloWorld.h文件。
3.在vc++6.0或者vs中创建dll工程,并将生成的HelloWorld.h文件引入。
4.创建c++的Person类
Person.h:
- #include <string>
- using namespace std;
- class Person{
- public:
- string name;
- int age;
- bool student;
- public:
- Person();
- Person(string name, int age, bool student);
- string toString();
- virtual ~Person();
- };
Person.cpp
- #include "Person.h"
- Person::Person()
- {
- }
- Person::Person(string name, int age, bool student):name(name), age(age), student(student){
- }
- string Person::toString(){
- string str = "name:" + this->name;
- return str;
- }
- Person::~Person()
- {
- }
5.实现HelloWorld.cpp:
- #include "jni.h"
- #include "HelloWorld.h"
- #include "Person.h"
- #include <iostream>
- using namespace std;
- JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj){
- cout << "Hello World!" << endl;
- }
- JNIEXPORT void JNICALL Java_HelloWorld_displayPerson(JNIEnv *env, jobject obj1, jobject obj){
- Person *p = new Person();
- jclass cls = (env)->GetObjectClass(obj);
- jfieldID name = env->GetFieldID(cls, "name", "Ljava/lang/String;");
- jstring str1 = (jstring)env->GetObjectField(obj, name);
- jboolean c = '1';
- string str = env->GetStringUTFChars(str1, &c);
- jfieldID age = env->GetFieldID(cls, "age", "I");
- p->name = str;
- p->age = env->GetIntField(obj, age);
- // p->student = obj.student;
- cout << p->toString() << " age:" << p->age << endl;
- }
6.在工程中导入“JDKpath”/include中的“jni.h”以及“JDKpath”/include/win32中的“jni_md.h”
7.生成dll,并将dll放入java工程的目录里
8.运行java
Java HelloWorld
总结:传递java对象,对象的各个属性需要与jni提供的类型进行转换然后再赋值给c++的对象,还是比较麻烦的,不知道有没有更好的方法。。。