您的位置:首页 > 运维架构 > Linux

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

2016-07-12 17:07 846 查看
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、结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: