JAVA calls c++ dynamic link library through JNA
1. C++ dynamic link library compilation
(1) Operating principle of dynamic link library
(2) Compile command
-
gcc -fPIC -i $JAVA_HOME/include -i $JAVA_HOME/include/linux -shared -o lib(name).so (dynamic link library name).c
gcc -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -shared -o libhello.so hello.c
-
PIC makes the code segment of the .so file into a real sense of sharing, and it is impossible to build a shared library without the -fPIC option on some architectures.
2. Java side
(1) Import dependencies
<dependencies>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.11.0</version>
</dependency>
</dependencies>
(2) Code implementation
- Define interface integration Library
- Use Native.load to load the dynamic link library
- Define the functions that need to be used in the interface
package com.ljn.Jna;
import com.sun.jna.Library;
import com.sun.jna.Native;
/**
* 运行环境是linux,需要打包生成jar文件放到linux环境运行
*/
class HelloJNA {
/**
* 定义一个接口,默认的是继承Library ,如果动态链接库里的函数是以stdcall方式输出的,那么就继承StdCallLibrary
* 这个接口对应一个动态链接(SO)文件
*/
public interface LibraryAdd extends Library {
// 这里使用绝对路径加载动态链接库
LibraryAdd LIBRARY_ADD = Native.load("/home/ljn/program/cpp/libhello.so", LibraryAdd.class);
/**
* 接口中只需要定义你要用到的函数或者公共变量,不需要的可以不定义
* 映射libadd.so里面的函数,注意类型要匹配
*/
int add(int a, int b);
}
public static void main(String[] args) {
// 调用so映射的接口函数
int add = LibraryAdd.LIBRARY_ADD.add(10, 15);
System.out.println("相加结果:" + add);
}
}
<br>
(3) Packaged as a jar package
3. Integrated operation
- Put the generated dynamic link library in the /home/ljn/program/cpp directory in linux
- Upload the packaged jar package in the /home/ljn/program/cpp directory in linux
- Run: java -jar