LINUX 下 JNA 调用 so--C++编译版本

项目中需要用到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); 
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值