C头文件
#ifndef __JNATEST_H__ #define __JNATEST_H__ #define LOG_HERE() printf("%s-%d\n", __func__, __LINE__) void test_jna(); #endif
C代码
#include <stdio.h> #include "jnatest.h" void test_jna() { LOG_HERE(); printf("called from JAVA\n"); } JAVA代码 import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; public class JnaTest { //继承Library,用于加载库文件 public interface CLibrary extends Library { CLibrary INSTANCE = (CLibrary) Native.loadLibrary( (Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class); // 声明一个跟C语言的printf()一样的方法, void printf(String format, Object... args); } public interface TestLibrary extends Library { TestLibrary INSTANCE = (TestLibrary) Native.loadLibrary("jnatest", TestLibrary.class); void test_jna(); } public static void main(String[] args) { //调用 CLibrary.INSTANCE.printf("From JAVA To C, year=%d\n", 2022); TestLibrary.INSTANCE.test_jna(); } }
安装依赖库
sudo apt install -y openjdk-8-jdk sudo apt install -y libjna-java sudo apt install -y libjna-platform-java
编译
gcc -fPIC -shared -o libjnatest.so jnatest.c sudo ldconfig javac -extdirs /usr/share/java JnaTest.java
测试
USJ_DIR=/usr/share/java CLASS_DIRS=. CLASS_DIRS=${CLASS_DIRS}:${USJ_DIR}/jna.jar CLASS_DIRS=${CLASS_DIRS}:${USJ_DIR}/jna-platform.jar java \ -cp ${CLASS_DIRS} \ JnaTest