Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
This paper mainly describes the use of JNA to simulate a struct and pass a struct array as an argument to the corresponding method.
The C language structure is defined as follows:
[CPP]View PlainCopy
- typedef struct Rect
- {
- int top;
- int bottom;
- int left;
- int right;
- } RECT;
JNA simulates the structure:
Need to introduce:
Import com.sun.jna.*;
Import com.sun.jna.ptr.*;
[Java]View PlainCopy
- Rect struct BODY
- Public static class Rect extends Structure {
- The order of the public fields in the//structure subclass must match the order of the structures in the C language, otherwise it will be an error!
- public int top;
- public int bottom;
- public int left;
- public int right;
- public static class Byreference extends Rect implements Structure.byreference {}
- public static class Byvalue extends Rect implements Structure.byvalue {}
- @Override
- protected List Getfieldorder () {
- return Arrays.aslist (new string[]{"Top", "bottom", "left", "right"});
- }
- }
Now to pass a struct array object to the method, how do you do it?
C Language Functions:
[CPP]View PlainCopy
- Rects: struct array, len: array length
- void function (rect* rects, int len);
The JNA simulation is as follows:
[Java]View PlainCopy
- void function (rect[] rects,int len);
Create an array and invoke the following method:
[Java]View PlainCopy
- int len = 5;
- Defining arrays
- rect[] Array = (rect[])new Rect (). ToArray (len);
- function (array, len);
Note that the creation of an array here uses the JNA ToArray () method instead of the Java general method of creating an array because the memory space is discontinuous in Java, and the JNA definition array is required to use the ToArray method so that the instantiated array memory space is contiguous.
In fact, here is mainly the creation of the structure of the array of places to note that if created using the following way, it will produce an empty array, the request is not space:
[Java]View PlainCopy
- int len = 5;
- rect[] Array = new Rect[len];
After this code executes, array=null, that is, the creation of the array failed!
Cause: Memory space in Java is discontinuous, JNA definition array is required to use the ToArray method, so that the instantiation of the array memory space is continuous, otherwise the first piece of data is correct, the other is misplaced.
See another article: http://tcspecial.iteye.com/blog/1665583
http://blog.csdn.net/zht666/article/details/38658985//Original address
JNA parameter passing problem, Java array