JNI 简单例子小结 (调用外部DLL)

1. 编写所需要调用到C DLL的java源文件,这里取名为TestJNI.java,放置在D:/根目录。

package myTest;

public class TestJNI{
  
  private native int add(int x,int y);
  
  public static void main(String[] args) {
    TestJNI testJNI = new TestJNI();
    int result = testJNI.add(1, 2);
    System.out.println("result = " + result);
  }

  static {
    System.loadLibrary("myDll");
  }
}
 

2. 产生头文件TestJNI.h。首先编译TestJNI.java。cmd到D:/根目录运行:javac -d d:/ TestJNI.java,然后运行javah myTest.TestJNI,则会生成TestJNI.h。其中的内容为:

#include "jni.h"
#ifndef _Included_TestJNI
#define _Included_TestJNI
#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jint JNICALL Java_myTest_TestJNI_add  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

注:最后要运行TestJNI的时候,在D:/根目录下运行 java myTest.TestJNI 就可以了。

3. 创建一个VC++空项目,用于生成一个myFirstDll.dll。而这个dll会在myDll.dll中被调用。往空项目中有新添加入两个文件First.h和First.c,内容为:

First.h
---------

#ifndef FIRST_H
#define FIRST_H

_declspec(dllexport) int myAdd(int, int);

#endif

First.c
---------

#include "First.h"

_declspec(dllexport) int myAdd(int i, int j)
{
 return i + j;
}

随后编译项目,可得到myFirstDll.lib和myFirstDll.dll文件。

4. 新建一个VC++空项目,创建一个新文件myDll.c,将上面生成的myFirstDll.lib,myFirstDll.dll和First.h拷贝到这个新项目中,将第2步产生的TestJNI.h文件也拷贝到这个项目中。编辑myDll.c的内容为:

myDll.c
------------

#include "TestJNI.h"
#include "First.h"

JNIEXPORT jint JNICALL Java_myTest_TestJNI_add
  (JNIEnv *ev, jobject obj, jint x, jint y)
{
 return myAdd(x, y);
}

 在VC项目的C/C++属性的Additional Include Directories中添加%JAVA_HOME%/include/;%JAVA_HOME%/include/win32。然后可以编译项目生成myDll.dll。

5. 将myFirstDll.dll,myDll.dll拷贝到D:/根目录。运行java myTest.TestJNI,就会输出1+2的结果3了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值