1. 程式人生 > >JNA呼叫C語言動態連結庫學習實踐總結

JNA呼叫C語言動態連結庫學習實踐總結

2.JNA模擬普通傳值引數

C語言函式:

int function1(int a, float b, long c)

JNA模擬:

int function1(int a, float b, long c)

3.JNA模擬C語言陣列

C語言函式:

void function1(char * data)

void function2(const unsigned char* data)

JNA模擬:

void function1(char[] data) 或者 void function1(byte[] data)
void function2(char[] data) 或者 void function2(byte[] data)

4.JNA模擬基本型別指標

JNA的ByReference有很多子類,這些類都在com.sun.jna.ptr包中:

IntByReference,LongByReference,FloatByReference,DoubleByReference,ShortByReference、ByteByReference、PointerByReference等等

從這些名字大家應該可以看出來他們的作用。

下面直接上例子吧:

C語言函式:

long function(int * a, long * b, float * c, double * d, short * e)

JNA模擬:

long function(IntByReference aRef, LongByReference bRef, FloatByReference cRef, DoubleByReference dRef, ShortByReference eRef)

如何構建這些物件呢?

FloatByReference cRef = new FloatByReference(); //使用預設初始值(具體多少我也不知道)
FloatByReference cRef = new FloatByReference(0); //初始值為0

呼叫方法和普通引數一樣:

function(…, cRef, …);

獲取結果值:

float fVal = cRef.getValue();

JNA都為我們做的很簡單,不是嗎?

5.JNA模擬指標、指標的指標、模擬void ,void 等指標*

C函式:

void function(int * pInt, int * ppInt, void

pVoid, void ** ppVoid)

JNA模擬:

void function(IntByReference pInt, PointerByReference ppInt, Pointer pVoid, PointerByReference ppVoid)
呼叫舉例:
IntByReference pInt = new IntByReference(0);
PointerByReference ppInt = new PointerByReference(Pointer.NULL); //指向指標的指標,初始化為NULL
Pointer pVoid = Pointer.NULL; //建立一個指向NULL的指標
PointerByReference ppVoid = new PointerByReference(Pointer.NULL);
呼叫:function(pInt, ppInt, pVoid, ppVoid);

(1)PointerByReference是指向指標的指標,遇到指標的指標都可以使用它來模擬,那麼如何獲取到它指向的指標呢?

Pointer p = ppVoid.getValue(); //獲取指標

(2)如何獲取指標的指標呢?

Pointer p1 = ….;
PointerByReference pp1 = new PointerByReference(p1);
PointerByReference ppp1 = new PointerByReference(pp1.getPointer());

這些操作大家可以自己做實驗嘗試,對於PointerByReference物件,getValue()是取值,而getPointer()是取這個指標的指標。

看著複雜,其實都很簡單!JNA要比JNI好用多了。