创建dll动态链接库,并使用java调用

参考文章:http://www.cnblogs.com/matthew-2013/p/3480296.html

              http://blog.csdn.net/g710710/article/details/7255744

首先探讨何为动态链接库,按照百毒百科的解释:

【动态链接库(Dynamic Link Library 或者 Dynamic-link Library,缩写为 DLL),是微软公司在微软Windows操作系统中,实现共享函数库概念的一种方式。这些库函数的扩展名是 ”.dll"、".ocx"(包含ActiveX控制的库)或者 ".drv"(旧式的系统驱动程序)。
动态链接提供了一种方法,使进程可以调用不属于其可执行代码的函数。函数的可执行代码位于一个 DLL 文件中,该 DLL 包含一个或多个已被编译、链接并与使用它们的进程分开存储的函数。DLL 还有助于共享数据和资源。多个应用程序可同时访问内存中单个 DLL 副本的内容。
使用动态链接库可以更为容易地将更新应用于各个模块,而不会影响该程序的其他部分。例如,您有一个大型网络游戏,如果把整个数百MB甚至数GB的游戏的代码都放在一个应用程序里,日后的修改工作将会十分费时,而如果把不同功能的代码分别放在数个动态链接库中,您无需重新生成或安装整个程序就可以应用更新。】

vs2012创建项目,win32 - win32项目,名称MyDLL。应用程序设置,选择DLL选项。

新建头文件testdll.h

#ifndef TestDll_H_
#define TestDll_H_
#ifdef MYLIBDLL
#define MYLIBDLL extern "C" _declspec(dllimport) 
#else
#define MYLIBDLL extern "C" _declspec(dllexport) 
#endif
MYLIBDLL int Add(int plus1, int plus2);
//You can also write like this:
//extern "C" {
//_declspec(dllexport) int Add(int plus1, int plus2);
//};
#endif

新建cpp testdll.cpp

#include "stdafx.h"
#include "testdll.h"
#include <iostream>
using namespace std;
int Add(int plus1, int plus2)
{
    int add_result = plus1 + plus2;
    return add_result;
}

在源文件目录下新建mydll.def

LIBRARY "MyDLL"
EXPORTS
Add @1

dllmain.cpp是自动创建的,定义了dll应用程序的入口

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

之后,编译,生成。

在workspace的MyDLLDebug目录即可找到生产的MyDLL.dll。

将该dll文件放到jdk的bin目录下。

打开eclipse,随意新建个项目。testdll

加入依赖的jna的jna-4.2.2.jar包。

 写代码:

package testdll;

import com.sun.jna.Native;
import com.sun.jna.win32.StdCallLibrary;

/**
 * @author sonne
 */
public class JNA {
    public interface CLibrary extends StdCallLibrary {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary("MyDLL.dll", CLibrary.class);
        int Add(int plus1, int plus2);
    }

    public static void main(String[] args) {
        int result = CLibrary.INSTANCE.Add(1,2);
        System.out.println("结果为" + result);
    }
}

这里需要定义java接口,该接口中方法与dll库函数方法一致,通过jna来调用这个接口实际上就是调用dll动态链接库。运行结果为,3。

可知是调用了dll的Add方法。求得1+2=3.

原文地址:https://www.cnblogs.com/rixiang/p/6593095.html