分享

Java中调用dll动态库的简洁方法

 昵称5943209 2011-05-14

Java中调用dll动态库的简洁方法

                

来源http://www.

Java中调用dll动态 库的简洁方法,Java中调用DLL方法,是通过JNI接口实现的。大概是先用Java写一个接口类,然后用javah 生成一个xxx.hc语言的头文件,然后用C实现这个头文件,在这个实现接口中调用其他已经实现的接口。

解压JNative-1.3.2.zip 获得三个文件,分别是:JNativeCpp.dlllibJNativeCpp.soJNative.jar JNativeCpp.dll Windows下用的,拷到windows / system32目录下;

libJNativeCpp.so Linux下使用的;

JNative.jar 这是一个扩展包,加载到你的程序中就可以。

一个简单例子

import org.xvolks.jnative.JNative;

import org.xvolks.jnative.Type;

import org.xvolks.jnative.exceptions.NativeException;

public class JNativeTest {

public static final int messageBox(int parentHandle, String message,

String caption, int buttons){// throws NativeException, IllegalAccessException {

JNative n = null;

try {

n = new JNative("User32.dll", "MessageBoxA"); //.dll”不用也可以, 常量DLL_NAME的值为User32.dll

// 构造JNative时完成装载User32.dll,并且定位MessageBoxA方法

n.setRetVal(Type.INT); // 指定返回参数的类型

int i = 0;

n.setParameter(i++, Type.INT, "" + parentHandle);

n.setParameter(i++, Type.STRING, message);

n.setParameter(i++, Type.STRING, caption);

n.setParameter(i++, Type.INT, "" + buttons); // 指定位置上的参数类型和值

n.invoke(); // 调用方法

return Integer.parseInt(n.getRetVal());

}

catch(Exception ex){

ex.printStackTrace();

}

finally {

if (n != null)

try {

n.dispose();

} catch (NativeException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} // 记得释放

}

return 0;

}

public static void main(String[] args) throws NativeException, IllegalAccessException{

JNativeTest.messageBox(100,"这是使用jnative练习", "jnativetest", 1);

}

}

关于linux下编译 C代码部分说明:

对于linux不同版本,可能会导致libJNativeCpp.so不同

原带的libJNativeCpp.so 是在glic2.4下编译的

为了适应glic2.3的情况,重新编译了libJNativeCpp.so,在for gcc3.4.6 glibc 2.3下。

编译办法:

JNative-1.3.2-src\JNativeCpp\Release目录下

1、备份calls.o asm_io.o这两个Object文件

2make clean

3、恢复到当前目录calls.o asm_io.o这两个Object文件

4make

目前已经修改了Release目录下的makefilesubdir.mk文件,使得在make clean的时候不删除calls.o asm_io.o两个文件

附:linux 动态库搜索路径:

export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH

makefile 文件

################################################################################

# Automatically-generated file. Do not edit!

################################################################################

-include ../makefile.init

RM := rm -rf

# All of the sources participating in the build are defined here

-include sources.mk

-include subdir.mk

-include objects.mk

ifneq ($(MAKECMDGOALS),clean)

ifneq ($(strip $(C++_DEPS)),)

-include $(C++_DEPS)

endif

ifneq ($(strip $(CC_DEPS)),)

-include $(CC_DEPS)

endif

ifneq ($(strip $(C_DEPS)),)

-include $(C_DEPS)

endif

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多