JNative入門使用--簡化windows和linux調用DLL的過程


JNative官方主頁:

http://jnative.free.fr/SPIP-v1-8-3/

http://sourceforge.net/projects/jnative/

JNative是可以方便地調用DLL, 相對於JNI來說, 非常的方便, 使用和學習也是很簡單. 現在該項目已經很久未更新了. 目前最新版是1.4 RC3.

注意事項: JNative只支持32位的JDK, 64位的系統需要安裝32位的JDK來使用JNative, 否則或報錯:

java.lang.IllegalStateException: JNative library not loaded, sorry !

我個人覺得, 錯誤原因是JNative本身需要加載一個JNativeCpp.dll, 這個dll是在32位系統下編譯的, 64位JDK加載的時候, 會導致加載不成功.

1.4 RC3的JNative.jar中的lib-bin中自帶了JNativeCpp.dll, 所以不需要再為JNative.jar配置JNativeCpp.dll.

使用eclipse, 直接添加JNative.jar, 使用32位的JDK就可以使用JNative了.

使用示例: http://www.iteye.com/topic/284818

1. 編譯自己的dll

test.h 頭文件(考慮了GCC和MS VC兩種編譯器)

#ifndef _TEST_H__  
#define _TEST_H__

#ifdef _MSC_VER
_declspec(dllexport) int add(int a,int b);
#endif

#ifdef __GNUC__
int add(int a,int b);
#endif

#endif

test.c

#include <stdio.h>
#include "test.h"

int add(int a, int b)
{
printf("dll function add() called\n");
return (a + b);
}

這里使用MinGW來進行編譯, 需要先安裝MinGW

gcc -Wall -shared test.c -o test.dll 

如果使用微軟的編譯器cl的話, 編譯命令為

cl test.c /link /out:test.dll /dll /OPT:NOWIN98 /machine:x86

這樣就獲得了test.dll文件

2. 下面使用JNative來調用自己的dll中的函數add

import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;

// 使用32位jdk
public class Test {
public static int nativeAdd(int a, int b) throws NativeException, IllegalAccessException {
JNative n = null;
n = new JNative("test.dll", "add");
n.setRetVal(Type.INT);
n.setParameter(0, a);
n.setParameter(1, b);
n.invoke();
System.out.println("返回: " + n.getRetVal());
return Integer.parseInt(n.getRetVal());
}

public static void main(String[] args) {
try {
nativeAdd(1, 2);
} catch (NativeException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

test.dll放在eclipse工程根目錄下即可.

測試結果如下:

返回: 3
dll function add() called

說明:

上面給的鏈接中的例子, 有try...finally..., 在finally中有如下代碼

if (n != null)  
n.dispose();

根據1.4 RC3的源代碼中, 我們可以看到整個方法已經被注釋.

 /**
* <p>
* This method does nothing!
* </p>
*
@deprecated this method does nothing

*
@exception NativeException
*
@exception IllegalAccessException
* if <code>dispose()</code> have already been called.
*
*/
@Deprecated
public final void dispose() throws NativeException, IllegalAccessException
{
/*
throwClosed();

synchronized (mLibs)
{
LibDesc libDesc = getLibDesc(mDllName);
libDesc.numHolders--;
if(libDesc.numHolders == 0)
{
nDispose(mJNativeHModule);
mIsClosed = true;
mLibs.remove(mDllName);
}
}
*/
}


總結

使用JNative可以方便地調用已有的dll, 可以提高系統的性能, 方便了跨語言的調用, JNative本省支持windows和linux, 也增強了自身的移植性, JNative本身的想法和出發點都是非常好的, 使用更加Java的方式來調用dll.

這個類庫已經很久未更新, 所以使用的時候還是要慎重考慮.

本文只是簡單的介紹, 還有很多不全面的地方, 歡迎拍磚!








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM