假设你须要在Scala或是Java中调用C或C++函数库,就须要使用JNI。 这里就涉及到编译scala ,java 和C(C++)代码,在这里给出一个程序的框架,我们使用sbt 缺省的代码文件夹
文件文件夹
src
—>main
——–>java
——–>scala
——–>c
当中文件夹c存放C++代码 ,java文件夹放置Java代码, scala文件夹放置Scala代码
项目组用来编译的相关文件为build.sbt 和Makefile (它编译放置在c文件夹下的C++文件,注意仅仅能编译C++,假设你有须要编译C,须要自行改动Makefile)
改动库文件名称为自己所需的名称
改动build.sbt 中的项目名称
3 |
version := "0.0.1-SNAPSHOT" |
5 |
organization := "com.guidebee" |
改动Makefile的库文件名称称
1 |
#### PROJECT SETTINGS #### |
2 |
# The name of the executable to be created |
4 |
BIN_NAME= $(SODIR)/libjnidemo.so |
改动Java引用的库文件名称称:
2 |
System.loadLibrary("jnidemo"); |
环境变量设置
在你设置好sbt的编译环境后,注意设置 JAVA_HOME 和 LD_LIBRARY_PATH 环境变量 ,Java_HOME为你Java的安装文件夹, 能够使用
export LD_LIBRARY_PATH = $LD_LIBRARY_PATH:./:./target/so
将编译后的库文件加入到 java.library.path 路径中(这样Java代码能够找到库文件所在文件夹)
编译和执行
编译使用指令 sbt compile
1 |
[email protected]:/sdb/jni# sbt compile |
2 |
[info] Set current project to JNIDemo (in build file:/mnt/sdb1/jni/) |
3 |
[info] Compiling 3 Java sources to /mnt/sdb1/jni/target/scala-2.10/classes... |
5 |
Beginning release build |
6 |
Compiling: src/main/c/IntArray.cpp -> build/release/IntArray.o -Wall -Wextra -g -fPIC -c -O -m64 -Wunused-parameter |
7 |
src/main/c/IntArray.cpp:21:1: warning: unused parameter ‘obj’ [-Wunused-parameter] |
8 |
Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr) |
10 |
Compile time: 00:00:00 |
11 |
Compiling: src/main/c/Prompt.cpp -> build/release/Prompt.o -Wall -Wextra -g -fPIC -c -O -m64 -Wunused-parameter |
12 |
src/main/c/Prompt.cpp: In function ‘_jstring* Java_Prompt_getLine(JNIEnv*, jobject, jstring)’: |
13 |
src/main/c/Prompt.cpp:24:13: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] |
16 |
src/main/c/Prompt.cpp: At global scope: |
17 |
src/main/c/Prompt.cpp:22:1: warning: unused parameter ‘obj’ [-Wunused-parameter] |
18 |
Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt) |
20 |
Compile time: 00:00:00 |
22 |
Linking: target/so/libjnidemo.so |
23 |
#@g++ build/release/IntArray.o build/release/Prompt.o -fPIC -o target/so/libjnidemo.so |
25 |
Making library: target/so/libjnidemo.so -> target/so/libjnidemo.so |
26 |
Total build time: 00:00:00 |
27 |
[success] Total time: 1 s, completed 29/08/2014 10:10:19 PM |
执行
sbt run
1 |
[email protected]:/sdb/jni# sbt run |
2 |
[info] Set current project to JNIDemo (in build file:/mnt/sdb1/jni/) |
4 |
[info] User typed: hello |
7 |
[success] Total time: 0 s, completed 29/08/2014 10:10:54 PM |
删除编译结果
sbt clean
1 |
[email protected]:/sdb/jni# sbt clean |
2 |
[info] Set current project to JNIDemo (in build file:/mnt/sdb1/jni/) |
3 |
[info] Updating {file:/mnt/sdb1/jni/}jni... |
4 |
[info] Resolving org.fusesource.jansi#jansi;1.4 ... |
6 |
Deleting target/so/libjnidemo.so symlink |
8 |
[success] Total time: 1 s, completed 29/08/2014 10:11:35 PM |
Github 代码
本例模板代码能够在 https://github.com/guidebee/JNIDemo下载。
时间: 2024-10-12 18:17:06