LINUX 下 JNA 调用 so--正确版
2014-03-16 10:14
501 查看
项目中需要用到JAVA调用c++,了解过JNI,但比较复杂,后来看到JNA(JNI的加强版)。
网上看了很多例子,但是始终出错,主要错误原因是undefined symbol,找不到c++ 方法。
教程的有些细节没说(- -||),好吧,我把成功的例子贴一下吧。
1.编写C++ so库
c++代码:注意加上extern “C”,否则无法找到c++方法。
#include <stdlib.h>
#include <iostream>
using namespace std;
extern "C"
{
void test() {
cout << "TEST" << endl;
}
int addTest(int a,int b)
{
int c = a + b ;
return c ;
}
}
编译so:g++ -fpic -shared -o libtest.so test.cpp
我把so文件放到了 /lib 下。
2.JAVA代码
import com.sun.jna.Library;
import com.sun.jna.Native;
public class jnatest1 {
// 继承Library,用于加载库文件
public interface Clibrary extends Library {
// 加载libhello.so链接库
Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",
Clibrary.class);
// 此方法为链接库中的方法
void test();
int addTest(int a,int b);
}
public static void main(String[] args) {
// 调用
Clibrary.INSTANTCE.test();
int c = Clibrary.INSTANTCE.addTest(10,20);
System.out.println(c);
}
}
网上看了很多例子,但是始终出错,主要错误原因是undefined symbol,找不到c++ 方法。
教程的有些细节没说(- -||),好吧,我把成功的例子贴一下吧。
1.编写C++ so库
c++代码:注意加上extern “C”,否则无法找到c++方法。
#include <stdlib.h>
#include <iostream>
using namespace std;
extern "C"
{
void test() {
cout << "TEST" << endl;
}
int addTest(int a,int b)
{
int c = a + b ;
return c ;
}
}
编译so:g++ -fpic -shared -o libtest.so test.cpp
我把so文件放到了 /lib 下。
2.JAVA代码
import com.sun.jna.Library;
import com.sun.jna.Native;
public class jnatest1 {
// 继承Library,用于加载库文件
public interface Clibrary extends Library {
// 加载libhello.so链接库
Clibrary INSTANTCE = (Clibrary) Native.loadLibrary("hello",
Clibrary.class);
// 此方法为链接库中的方法
void test();
int addTest(int a,int b);
}
public static void main(String[] args) {
// 调用
Clibrary.INSTANTCE.test();
int c = Clibrary.INSTANTCE.addTest(10,20);
System.out.println(c);
}
}
相关文章推荐
- 10 篇对初学者和专家都有用的 Linux 命令教程
- Linux 与 Windows 对UNICODE 的处理方式
- Ubuntu12.04下QQ完美走起啊!走起啊!有木有啊!
- 解決Linux下Android开发真机调试设备不被识别问题
- 运维入门
- 运维提升
- Linux 自检和 SystemTap
- Ubuntu Linux使用体验
- c语言实现hashmap(转载)
- Linux 信号signal处理机制
- linux下mysql添加用户
- 关于指针的一些事情
- Scientific Linux 5.5 图形安装教程
- 基于 Linux 集群环境上 GPFS 的问题诊断
- 谁是桌面王者?Win PK Linux三大镇山之宝
- vivi下重新调整分区
- Linux VS Unix:Linux欲一统天下 Unix不死
- linux下设定环境变量
- Linux下修改MySQL编码的方法