关于JNI入门,这篇文章值得一看:https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
以下为本人在Ubuntu下的实践。
首先写java文件:
public class HelloNative {
static {
System.loadLibrary("HelloNative");
}
private static native void sayHello();
@SuppressWarnings("static-access")
public static void main(String[] args) {
new HelloNative().sayHello();
}
}
这里注意最好不要添加包名,否则生成h文件会比较难处理。
然后生成.class文件和.h文件:
/* 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: sayHello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloNative_sayHello
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
使用C++编写sayHello函数如下:
#include <jni.h>
#include <iostream>
#include "HelloNative.h"
using namespace std;
// Implementation of native method sayHello() of HelloJNI class
JNIEXPORT void JNICALL Java_HelloNative_sayHello(JNIEnv *, jclass){
cout << "Hello World from C++!" << endl;
return;
}
然后编译生成.dll文件:
The program 'x86_64-w64-mingw32-g++' is currently not installed. You can install it by typing:
sudo apt-get install g++-mingw-w64-x86-64
提示未安装,那就按照提示安装一下命令。过程不是很顺利,第一次尝试未完成安装,根据提示添加
fix-missing
后安装成功,但再次运行时又遇到了问题:
fatal error: jni.h: No such file or directory
#include <jni.h>
第一次运行配置环境总会花很多精力,使用locate jni.h
可查看jni.h的路径,其他文件类似。通过把缺失的.h文件复制到需要使用其的目录下解决问题(曲线救国哈哈)。
最后终于生成了.dll文件,尝试使用java命令运行程序的时候,又出问题了.
Exception in thread "main" java.lang.UnsatisfiedLinkError: no HelloNative in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)
at java.lang.Runtime.loadLibrary0(Runtime.java:870)
at java.lang.System.loadLibrary(System.java:1122)
at HelloNative.<clinit>(HelloNative.java:5)
应该是DLL文件生成有问题,后续待解决。
网友评论