jna调用so例子

来源:互联网 发布:真心和知真的意思 编辑:程序博客网 时间:2024/06/07 02:30


最近自己写的一个广告发布平台要迁移到Linux平台上,由于之前用的是windows平台的dll文件,现在要改用.so。讲下如何在Linux下面调用.so

在linux下使用jna调用本地方法的时候,需要将C写成的程序编译为so文件

1、写一个简单test.c文件:

#include<stdio.h>int add(int a,int b);int add(int a,int b){      int c = a + b ;      return c ;} 

2、编译为so动态链接
gcc -fpic -c test.cgcc -shared -o libtest.so test.ols看一下生成的文件:libtest.so test.c test.o

这样就会生成so文件了。 这里为什么要命名为libtest.so而不是test.so呢?因为jna在找so文件的时候,要匹配前缀为lib的so文件

3、接下来开始写java文件(需要下载jna.jar),我们写一个TestSo.java

import com.sun.jna.Library;import com.sun.jna.Native;public class TestSo {public interface LgetLib extends Library {// 调用linux下面的so文件,注意,这里只要写test就可以了,不要写libtest,也不要加后缀LgetLib INSTANCE = (LgetLib) Native.loadLibrary("test",LgetLib.class);int add(int a,int b);}public int add(int a,int b){return LgetLib.INSTANCE.add(a,b);}public static void main(String[] args) {TestSo ts = new TestSo();int c = ts.add(10,20);System.out.println("10+20="+c);}}
4、 接下来进行编译:

export CLASSPATH=$CLASSPATP:./jna.jar                         //这里是设置环境变量javac TestSo.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>

这里直接运行TestSo的话:

<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong> TestSoException in thread "main" <strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>.lang.UnsatisfiedLinkError: Unable to load library 'test': libtest.so: cannot open shared object file: No such file or directoryat com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:163)at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:236)at com.sun.jna.Library$Handler.<init>(Library.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:140)at com.sun.jna.Native.loadLibrary(Native.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:379)at com.sun.jna.Native.loadLibrary(Native.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:364)at TestSo$LgetLib.<clinit>(TestSo.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:7)at TestSo.add(TestSo.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:11)  at TestSo.main(TestSo.<strong style="color: black; background-color: rgb(255, 255, 102);">java</strong>:15)

这个错误是指找不到so文件。于是我们将so文件所在的目录设置到环境变量LD_LIBRARY_PATH中:

vim /etc/profile

在export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC下面加入

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${你的so目录}

之后,你可以检查一下设置的起没起效果:echo $LD_LIBRARY_PATH,如果出现你设置的内容就对了,如果没有,你可以重新打开一个窗口再查一下

设置好环境变量之后,你就可以运行java类了:

java TestSo
10+20=30

到此运行成功。

如果你遇到了紧急的情事,而这个地方又搞不定,你可以暂时交so文件放到/usr/lib这个目录下面,一般是可以使程序运行的。

0 0
原创粉丝点击