JNI方式调用dll或者.so(整套解决方案)

来源:互联网 发布:拳皇97mac免费版 编辑:程序博客网 时间:2024/05/16 09:12

1.写一个Java类,如

package test;

public class Hello{

static void copy() {
  // 获取服务器所使用的操作系统Windows或者Linux
  String osInfo = System.getProperty("os.name");
  String path="";
  String aPath="";
  File javaHello = null;
  String fileName = "";
  
  if (osInfo.toLowerCase().indexOf("windows") != -1){
   path = System.getProperty("java.library.path");
   aPath = path.substring(0, path.indexOf(';'));
   javahello= new File(aPath + File.separator + "jnihello.dll");
   fileName = "jnihello.dll";
  }
  else{
   path = System.getProperty("java.library.path");//将.dll或者.so拷贝到java.library.path下
   aPath = path.substring(0, path.indexOf(':'));
   javaencrypt = new File(aPath + File.separator + "libjnihello.so");//注意,如果在Linux操作系统下,必须加上前缀lib
   fileName = "libjnihello.so";
  }
  copyOne(javahello, fileName);

 }

 static void copyOne(File dest, String src) {
  InputStream inputStream = Hello.class
    .getResourceAsStream(src);
  FileOutputStream outputStream;
  try {
   outputStream = new FileOutputStream(dest);

   byte[] array = new byte[8192];
   for (int i = inputStream.read(array); i != -1; i = inputStream
     .read(array)) {
    outputStream.write(array, 0, i);
   }
   outputStream.close();
   inputStream.close();
  } catch (Exception e) {

  }

 }

 static {
  copy();
  String osInfo = System.getProperty("os.name");
  if (osInfo.toLowerCase().indexOf("windows") != -1){
   System.loadLibrary("jnihello");
  }
  else{
   System.loadLibrary("jnihello");
  }
 }

public native String sayHi(String name);//本地化方法,具体实现通过C或者C++语言内部实现

}

2.将java源文件编译成.class,并通过javah将class文件生成C语言的头文件javah -classpath . -jni  Hello生成一个Hello.h头文件

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

#ifndef _Included_Hello
#define _Included_Hello
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Hello
 * Method:    sayHi
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_Hello_sayHi
  (JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif
3.具体在C语言中实现

#include "Hello.h"
#include <windows.h>#linux中去掉
#include <iostream>
#include "d3des.c"

JNIEXPORT jstring JNICALL Java_Hello_sayHi  (JNIEnv * env, jobject, jstring key, jstring str){
      jstring string="Hello";
      return string;
  }

4.编译

5.可以直接使用Hello.java了

6.make.sh//Linux下编译C++,如果非C++,直接用gcc就可以了
rm -f hello.o
rm -f jni.o
rm -f libjnihello.so
gcc -c hello.c -I.
g++ -c hello.cpp -I. -I/home/wuhailin/bea/jdk150_11/include
g++ -shared -o libjnihello.so hello.o jni.o

原创粉丝点击