During JNA, how to map unsigned int is encountered, Because java does not have the unsigned type. If you still want to use the normal int type, then get abs.
I tried it and found that the last returned value is incorrect.
The code in DLL is as follows:
[Cpp]
Unsigned int add (unsigned int first, unsigned int second ){
Printf ("(c) test jna: % u + % u = % u \ n", first, second, first + second );
Return first + second;
}
Unsigned int add (unsigned int first, unsigned int second ){
Printf ("(c) test jna: % u + % u = % u \ n", first, second, first + second );
Return first + second;
}
Jna is called as follows:
[Cpp]
Int a = 0x80000000;
Int B = 0x70000000;
Int c = (TestJnaLib. INSTANCE. add (a, B ));
// C = c & 0 xffffffffl;
System. out. println ("a + B =" + c + "");
Int a = 0x80000000;
Int B = 0x70000000;
Int c = (TestJnaLib. INSTANCE. add (a, B ));
// C = c & 0 xffffffffl;
System. out. println ("a + B =" + c + "");
The result is as follows:
A + B =-268435456
(C) test jna: 2147483648 + 1879048192 = 4026531840
Change to c = Math. abs (c );
A + B = 268435456
The answer is still wrong. Think too. It was originally 32 bits. When a bits are used as the symbol bits and directly take the positive number, the original data will be lost because the symbol bit is gone.
After checking the internet, we found that we use long instead of unsigned int. However, if there is a problem, long is 64-bit. If it is replaced directly, it will inevitably cause an error.
After testing, the add function in JNA should be declared as follows:
[Java]
Int add (int first, int second );
Long add (int first, int second );
Int add (int first, int second );
Long add (int first, int second );
Both of them are acceptable, but in the second example, since long is 64-bit, it should overwrite the data in the stack, but the call is successful, which is hard to understand. However, we recommend that you use the first method, in this way, there is no problem in running the code in the DLL. If you need to set the value, you should take the following:
[Java]
Int a = 0x80000000;
Int B = 0x60000000;
System. out. println (a + "" + B + "");
Long c = (TestJnaLib. INSTANCE. add (B, ));
Long d = a + B;
D = d & 0 xffffffffl;
C = c & 0 xffffffffl;
System. out. println ("a + B =" + c + "");
System. out. println ("d:" + d + "");
Int a = 0x80000000;
Int B = 0x60000000;
System. out. println (a + "" + B + "");
Long c = (TestJnaLib. INSTANCE. add (B, ));
Long d = a + B;
D = d & 0 xffffffffl;
C = c & 0 xffffffffl;
System. out. println ("a + B =" + c + "");
System. out. println ("d:" + d + "");
You must use the & operator of the long type to retrieve the low 32 bits. By comparing d, the two are the same, indicating that this method is correct.
If the unsigned int type appears in the struct, it must be replaced by int instead of long. Otherwise, you will find that some data members will be overwritten.