jni例子

来源:互联网 发布:淘宝旺铺基础版装修 编辑:程序博客网 时间:2024/05/16 17:23
 

1.先用eclipse 创建 一个名字为HelloNative的类

public class HelloNative {

  public native int getCount(int cout);

}

2.再到cmd 命令下输入javah HelloNative  如果成功了就可以该类的目录下能看到 HelloNative.h的文件。

 

3.在用cmd命令输入 type helloNative.h  显示如下。这是我们想要的c或c++的头文件了。

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloNative */

#ifndef _Included_HelloNative
#define _Included_HelloNative
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloNative
 * Method:    getCount
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_HelloNative_getCount
  (JNIEnv *, jobject, jint);

#ifdef __cplusplus
}
#endif
#endif

4.创建一个c++dll 我用的是vs 2010 

 vs 2010 创建c++ dll过程:

创建一个win32控制台程序。 点击下一步。再选应用程序类型: 附加选项:选空项目

一个c++dll就创建完毕了。

在到源文件的目录下 创建一个名为hellojni.cpp

#include "HelloNative.h"
#include <iostream>
using namespace std;
JNIEXPORT jint JNICALL Java_HelloNative_getCount
 (JNIEnv * env, jobject obj, jint count)
{
 return count+10;
}

必须。 把jni.h  ,jni_md.h HelloNative.h导入工程里面

运行下。如果没有错就成99% .错了。如果错了. 多半是 helloNative.h  中#include <jni.h>这行代码在作怪.把他改成 #include “jni.h“

找到生成dll把它位置。设置到系统的环境变量里去。

5.重新修改HelloNative.java

public class HelloNative {

  public native int getCount(int cout);


  public static void main(String[] args) {
 
   HelloNative h=new HelloNative();
   System.loadLibrary("jnitest");
   System.out.println("=="+h.getCount(2));
}

}

如果报错多半没有找到jnitest 把eclipse 重启再试试。。

正确的运行结果是==12

jni你会了吗。。。

原创粉丝点击