打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
JNA调用C语言动态链接库学习实践总结 第2页

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好用多了。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
函数指针总结_
[原]C/C++:如何理解复杂的声明 - C/C++ - raof01-Haste mak...
你想错了,并不是所有指针都是4字节。
C语言中的函数指针学习笔记
第一部分 基础语言之六函数
JNA API Documentation
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服