windows/linux + java + jna + dll/so 调用C/C++

1、vs2013 新建win32 dll 空项目,main.h :

extern "C" _declspec(dllexport) void hello();
extern "C" _declspec(dllexport) int add(int first, int second);

2、main.cpp,然后生成dll文件 :

#include "main.h"
#include <iostream>

int add(int a, int b){
	return a + b;
}

void hello()
{
	printf("Hello World!\n");
}

3、eclipse 新建 java项目,把之前生成好的dll文件放在项目根目录,新建包、类,HelloWorld.java :

package com.busymonkey;

import com.sun.jna.Library;
import com.sun.jna.Native;

public class HelloWorld {

	public interface TestDll1 extends Library {
		TestDll1 INSTANCE = (TestDll1) Native.loadLibrary("javaJNA", TestDll1.class);
		public int add(int a, int b);  
	    public void hello();
	}

	public static void main(String[] args) {
		System.out.println(TestDll1.INSTANCE.add(1,2));
		TestDll1.INSTANCE.hello();
	}
}





项目添加 jna 的 jar 包:点击打开链接




第二篇:

上面是windows环境下java程序调用dll,以下是linxu环境 java程序调用so动态库:

1、新建一个main.cpp:(这里需要注意的是外部声明,不然找不到动态库中的函数)

#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 ;  
    }   
}

注:学过C/C++(cplusplus/cpp)的人都知道,extern是编程语言中的一种属性,它表征了变量、函数等类型的作用域(可见性)属性,是编程语言中的关键字。当进行编译时,该关键字告诉编译器它所声明的函数和变量等可以在本模块或者文件以及其他模块或文件中使用。通常,程序员都只是在“*h”(头文件)使用该关键字以限定变量或函数等类型的属性,然后在其他模块或本模块中使用。



2、编译so动态库文件(这里注意,linux扫描lib开头的so文件,但之后java程序中加载的时候不需要lib开头,也不需要.so后缀):

g++ -fpic -shared -o libtest.so main.cpp

为了之后的  java  程序能找到该动态库文件,加一下环境变量,并且 source 一下:

#vim /etc/profile
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$/opt/javaJNA


3、HelloWorld.java :

import com.sun.jna.Library;
import com.sun.jna.Native;

public class HelloWorld {

        public interface TestDll1 extends Library {
                TestDll1 INSTANCE = (TestDll1) Native.loadLibrary("test", TestDll1.class);
                void test();
                int addTest(int a, int b);
        }

        public static void main(String[] args) {
                TestDll1.INSTANCE.test();
                int c = TestDll1.INSTANCE.addTest(10, 20);
                System.out.println(c);
        }
}

同样在目录下拷贝好  jna  的  jar  包,然后编译生成:

 javac -classpath jna-3.5.1.jar HelloWorld.java



4、运行程序:

java -classpath .:jna-3.5.1.jar HelloWorld


5、结果:




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值