12月 092015
 

首先说明一下Java调用C程序的过程,下面这些内容从网上搜索到的结果:
转自:http://liufei-fir.iteye.com/blog/776326
用java调用dll本是一个不难的事情,但往往会给初学者带来的一点麻烦,网络上很多调用dll的例子都参差不齐,往往省略了一些步骤,对他们来说觉得简单不需要说明,对初学者来说确很重要,结果不想可知。因此在这里仔细的说明一下,希望给初学者们带来些许方便,高手绕过。。
一,首先在C盘建立项目文件夹jnitest,然后建立hello文件夹,在hello文件夹下放入Test.java,即在
C:\jnitest\hello下放入Test.java,
Test.java的内容为:
package hello;
class Test {
static {
System.loadLibrary(“TestDll”);
}
public static void main(String ar[]) {
System.out.println(“Hello world from Java”);
Test t = new Test();
int a = 1, b = 1;
int c = t.add(a, b);
System.out.println(c);
}
public native int add(int a, int b);
}
二,启动cmd命令行工具,切换到项目文件夹的目录(C:\jnitest>),然后输入javac hello\Test.java,即cmd最终显示为:C:\jnitest>javac hello\Test.java,接着执行C:\jnitest>javah hello.Test。所有命令
都注意下大小写。最终会在C:\jnitest下生成hello_Test.h头文件。
三,打开Vc++ 6.0,新建-》工程-》Win32 Dynamic-Link Library,工程名称为TestDll,点确定,然后
选择“一个简单的DLL工程”,按完成。
四,将hello_Test.h拷贝到VC的TestDll项目的文件夹下,在VC6.0界面中左方导航中选择“FileView”选择
Header Files点右键-》添加文件到目录,然后选中hello_Test.h。
五,打开TestDll.cpp,修改内容为:
// TestDll.cpp : Defines the entry point for the DLL application.
//
#include “stdafx.h”
#include “hello_Test.h”
JNIEXPORT jint JNICALL Java_hello_Test_add
(JNIEnv *, jobject, jint a, jint b)
{
return a+b;
}
六,点菜单“工具”-》选项-》目录,这里应添加jdk的头文件路径,添加两个。我的为H:\JDK1.5.0_16
\INCLUDE和H:\JDK1.5.0_16\INCLUDE\WIN32。
七,编译项目文件。
八,将编译生成的TestDll.dll拷贝到和hello_Test.h相同的目录下,在我这边既是C:\jnitest。(既C:\jnitest下有TestDll.dll和hello_Test.h)。
九,在cmd命令行C:\jnitest>下输入java hello.Test,即可看到结果。
十。输出为:Hello world from Java
2
这里补充说明的是,上述方法采取了命令行编译的方式,直接将dll放入.class文件所在文件夹,如果是使用eclipse,那么就需要将dll导入到工程中,具体的步骤如下:右单击项目名→导入→常规→文件系统→下一步→浏览→选择DLL文件所在目录→确定→勾选DLL文件→完成.
如果在得到dll后运行程序,出现no XXX in java.library.path异常,则说明dll没有找到,此时使用dll


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)