1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
|
/* Copyright (c) 2007-2009 Timothy Wall, All Rights Reserved
*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import com.sun.jna.Structure.FieldOrder;
import com.sun.jna.Structure.StructureSet;
import com.sun.jna.ptr.ByteByReference;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.LongByReference;
import junit.framework.TestCase;
/** TODO: need more alignment tests, especially platform-specific behavior
* @author twall@users.sf.net
*/
//@SuppressWarnings("unused")
public class StructureTest extends TestCase {
private static final String UNICODE = "[\u0444]";
public static void main(java.lang.String[] argList) {
junit.textui.TestRunner.run(StructureTest.class);
}
public void testSimpleSize() throws Exception {
class TestStructure extends Structure {
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
Structure s = new TestStructure();
assertEquals("Wrong size", 4, s.size());
}
public void testInitializeFromPointer() {
class TestStructureX extends Structure {
public int field1, field2;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field1", "field2");
}
public TestStructureX() {
}
public TestStructureX(Pointer p) {
super(p);
}
}
Structure s = new TestStructureX();
Pointer p = s.getPointer();
Structure s1 = new TestStructureX(p);
Pointer p1 = s1.getPointer();
assertEquals("Constructor address not used", p, p1);
assertFalse("Pointer should not be auto-allocated", p.getClass().equals(p1.getClass()));
assertNotSame("Initial pointer should not be used directly: " + p, p, p1);
}
public void testInitializeWithTypeMapper() {
class TestStructure extends Structure {
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
public TestStructure(TypeMapper m) {
super(ALIGN_DEFAULT, m);
}
}
TypeMapper m = new DefaultTypeMapper();
TestStructure s = new TestStructure(m);
assertEquals("Type mapper not installed", m, s.getTypeMapper());
}
// must be public to populate array
public static class TestAllocStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("f0", "f1", "f2", "f3");
public int f0;
public int f1;
public int f2;
public int f3;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testFieldsAllocated() {
class TestStructure extends Structure {
public TestStructure() { }
public TestStructure(Pointer p) { super(p); }
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
public int fieldCount() { ensureAllocated(); return fields().size(); }
}
TestStructure s = new TestStructure();
assertEquals("Wrong number of fields (default)", 1, s.fieldCount());
s = new TestStructure(new Memory(4));
assertEquals("Wrong number of fields (preallocated)", 1, s.fieldCount());
}
public void testProvidedMemoryTooSmall() {
class TestStructure extends Structure {
public TestStructure(Pointer p) { super(p); }
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
try {
new TestStructure(new Memory(2));
fail("Expect exception if provided memory is insufficient");
}
catch(IllegalArgumentException e) {
}
}
public void testClearOnAllocate() {
TestAllocStructure s = new TestAllocStructure();
s.read();
assertEquals("Memory not cleared on structure init", 0, s.f0);
assertEquals("Memory not cleared on structure init", 0, s.f1);
assertEquals("Memory not cleared on structure init", 0, s.f2);
assertEquals("Memory not cleared on structure init", 0, s.f3);
s = (TestAllocStructure)s.toArray(2)[1];
assertEquals("Memory not cleared on array init", 0, s.f0);
assertEquals("Memory not cleared on array init", 0, s.f1);
assertEquals("Memory not cleared on array init", 0, s.f2);
assertEquals("Memory not cleared on array init", 0, s.f3);
}
// cross-platform smoke test
public void testGNUCAlignment() {
class TestStructure extends Structure {
public byte b;
public short s;
public int i;
public long l;
public float f;
public double d;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("b", "s", "i", "l", "f", "d");
}
}
Structure s = new TestStructure();
s.setAlignType(Structure.ALIGN_GNUC);
final int SIZE = Native.MAX_ALIGNMENT == 8 ? 32 : 28;
assertEquals("Wrong structure size", SIZE, s.size());
}
// cross-platform smoke test
public void testMSVCAlignment() {
class TestStructure extends Structure {
public byte b;
public short s;
public int i;
public long l;
public float f;
public double d;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("b", "s", "i", "l", "f", "d");
}
}
Structure s = new TestStructure();
s.setAlignType(Structure.ALIGN_MSVC);
assertEquals("Wrong structure size", 32, s.size());
}
public static abstract class FilledStructure extends Structure {
private boolean initialized;
@Override
protected void ensureAllocated() {
super.ensureAllocated();
if (!initialized) {
initialized = true;
for (int i=0;i < size();i++) {
getPointer().setByte(i, (byte)0xFF);
}
}
}
}
// Do NOT change the order of naming w/o changing testlib.c as well
public static class TestStructure0 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1");
public byte field0 = 0x01;
public short field1 = 0x0202;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1" })
public static class AnnotatedTestStructure0 extends FilledStructure {
public byte field0 = 0x01;
public short field1 = 0x0202;
}
public static class TestStructure1 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1");
public byte field0 = 0x01;
public int field1 = 0x02020202;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1" })
public static class AnnotatedTestStructure1 extends FilledStructure {
public byte field0 = 0x01;
public int field1 = 0x02020202;
}
public static class TestStructure2 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1");
public short field0 = 0x0101;
public int field1 = 0x02020202;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1" })
public static class AnnotatedTestStructure2 extends FilledStructure {
public short field0 = 0x0101;
public int field1 = 0x02020202;
}
public static class TestStructure3 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1", "field2");
public int field0 = 0x01010101;
public short field1 = 0x0202;
public int field2 = 0x03030303;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1", "field2" })
public static class AnnotatedTestStructure3 extends FilledStructure {
public int field0 = 0x01010101;
public short field1 = 0x0202;
public int field2 = 0x03030303;
}
public static class TestStructure4 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1", "field2", "field3");
public int field0 = 0x01010101;
public long field1 = 0x0202020202020202L;
public int field2 = 0x03030303;
public long field3 = 0x0404040404040404L;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1", "field2", "field3" })
public static class AnnotatedTestStructure4 extends FilledStructure {
public int field0 = 0x01010101;
public long field1 = 0x0202020202020202L;
public int field2 = 0x03030303;
public long field3 = 0x0404040404040404L;
}
@FieldOrder({ "field0", "field1" })
public static class _InheritanceTestStructure4Parent extends FilledStructure {
public int field0 = 0x01010101;
public long field1 = 0x0202020202020202L;
}
@FieldOrder({ "field2", "field3" })
public static class InheritanceTestStructure4 extends _InheritanceTestStructure4Parent {
public int field2 = 0x03030303;
public long field3 = 0x0404040404040404L;
}
public static class TestStructure5 extends FilledStructure {
public static final List<String> FIELDS = createFieldsOrder("field0", "field1");
public long field0 = 0x0101010101010101L;
public byte field1 = 0x02;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
@FieldOrder({ "field0", "field1" })
public static class AnnotatedTestStructure5 extends FilledStructure {
public long field0 = 0x0101010101010101L;
public byte field1 = 0x02;
}
public interface SizeTest extends Library {
int getStructureSize(int type);
}
private void testStructureSize(int index) {
testStructureSize("", index);
}
private void testStructureSize(String prefix, int index) {
try {
SizeTest lib = Native.load("testlib", SizeTest.class);
Class<? extends Structure> cls = (Class<? extends Structure>) Class.forName(getClass().getName() + "$" + prefix + "TestStructure" + index);
Structure s = Structure.newInstance(cls);
assertEquals("Incorrect size for structure " + index + "=>" + s.toString(true), lib.getStructureSize(index), s.size());
}
catch(Exception e) {
throw new Error(e);
}
}
public void testStructureSize0() {
testStructureSize(0);
}
public void annotatedTestStructureSize0() {
testStructureSize("Eazy", 0);
}
public void testStructureSize1() {
testStructureSize(1);
}
public void annotatedTestStructureSize1() {
testStructureSize("Eazy", 1);
}
public void testStructureSize2() {
testStructureSize(2);
}
public void annotatedTestStructureSize2() {
testStructureSize("Eazy", 2);
}
public void testStructureSize3() {
testStructureSize(3);
}
public void annotatedTestStructureSize3() {
testStructureSize("Eazy", 3);
}
public void testStructureSize4() {
testStructureSize(4);
}
public void annotatedTestStructureSize4() {
testStructureSize("Eazy", 4);
}
public void inheritanceTestStructureSize4() {
testStructureSize("Inheritance", 4);
}
public void testStructureSize5() {
testStructureSize(5);
}
public void annotatedTestStructureSize5() {
testStructureSize("Eazy", 5);
}
public interface AlignmentTest extends Library {
int testStructureAlignment(Structure s, int type,
IntByReference offsetp, LongByReference valuep);
}
private void testAlignStruct(int index) {
testAlignStruct("", index);
}
private void testAlignStruct(String prefix,int index) {
AlignmentTest lib = Native.load("testlib", AlignmentTest.class);
try {
IntByReference offset = new IntByReference();
LongByReference value = new LongByReference();
Class<?> cls = Class.forName(getClass().getName() + "$" + prefix + "TestStructure" + index);
Structure s = Structure.newInstance((Class<? extends Structure>) cls);
int result = lib.testStructureAlignment(s, index, offset, value);
assertEquals("Wrong native value at field " + result
+ "=0x" + Long.toHexString(value.getValue())
+ " (actual native field offset=" + offset.getValue()
+ ") in " + s, -2, result);
}
catch(Exception e) {
throw new Error(e);
}
}
public void testAlignStruct0() {
testAlignStruct(0);
}
public void annotatedTestAlignStruct0() {
testAlignStruct("Annotated", 0);
}
public void testAlignStruct1() {
testAlignStruct(1);
}
public void annotatedTestAlignStruct1() {
testAlignStruct("Annotated", 1);
}
public void testAlignStruct2() {
testAlignStruct(2);
}
public void annotatedTestAlignStruct2() {
testAlignStruct("Annotated", 2);
}
public void testAlignStruct3() {
testAlignStruct(3);
}
public void annotatedTestAlignStruct3() {
testAlignStruct("Annotated", 3);
}
public void testAlignStruct4() {
testAlignStruct(4);
}
public void annotatedTestAlignStruct4() {
testAlignStruct("Annotated", 4);
}
public void inheritanceTestAlignStruct4() {
testAlignStruct("Inheritance", 4);
}
public void testAlignStruct5() {
testAlignStruct(5);
}
public void annotatedTestAlignStruct5() {
testAlignStruct("Annotated", 5);
}
public void testInheritanceFieldOrder() {
@FieldOrder({ "a", "b" })
class Parent extends Structure {
public int a;
public int b;
}
@FieldOrder({ "c", "d" })
class Son extends Parent {
public int c;
public int d;
}
Son test = new Son();
assertEquals("Wrong field order", Arrays.asList("a", "b", "c", "d"), test.getFieldOrder());
}
public void testStructureWithNoFields() {
class TestStructure extends Structure {
@Override
protected List<String> getFieldOrder() {
return Collections.emptyList();
}
}
try {
new TestStructure();
fail("Structure should not be instantiable if it has no public member fields");
}
catch(IllegalArgumentException e) {
// expected - ignored
}
}
public void testAnnotatedStructureWithNoFields() {
class TestStructure extends Structure {
}
try {
new TestStructure();
fail("Structure should not be instantiable if it has no public member fields");
}
catch(IllegalArgumentException e) {
// expected - ignored
}
}
public void testAnnotatedStructureWithNoFieldsWithAnnot() {
@FieldOrder({ })
class TestStructure extends Structure {
}
try {
new TestStructure();
fail("Structure should not be instantiable if it has no public member fields");
}
catch(IllegalArgumentException e) {
// expected - ignored
}
}
public void testStructureWithOnlyNonPublicMemberFields() {
class TestStructure extends Structure {
int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
try {
new TestStructure();
fail("Structure should not be instantiable if it has no public member fields");
}
catch(Error e) {
// expected - ignored
}
}
// must be publicly accessible in order to create array elements
public static class PublicTestStructure extends Structure {
public static class ByValue extends PublicTestStructure implements Structure.ByValue {
public ByValue() { }
public ByValue(Pointer p) { super(p); }
}
public static class ByReference extends PublicTestStructure implements Structure.ByReference {
public ByReference() { }
public ByReference(Pointer p) { super(p); }
}
public static final List<String> FIELDS = createFieldsOrder("x", "y");
public int x = 1, y = 2;
public PublicTestStructure() { }
public PublicTestStructure(Pointer p) { super(p); read(); }
public static int allocations = 0;
@Override
protected void allocateMemory(int size) {
super.allocateMemory(size);
++allocations;
}
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testStructureField() {
class TestStructure extends Structure {
public PublicTestStructure s1, s2;
public int after;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("s1", "s2", "after");
}
}
TestStructure s = new TestStructure();
TestStructure s2 = new TestStructure();
assertNotNull("Inner structure should be initialized", s.s1);
assertNotNull("Inner structure should be initialized (cached)", s2.s1);
assertEquals("Wrong aggregate size",
s.s1.size() + s.s2.size() + 4, s.size());
s.write();
assertEquals("Wrong memory for structure field 1 after write",
s.getPointer(), s.s1.getPointer());
assertEquals("Wrong memory for structure field 2 after write",
s.getPointer().share(s.s1.size()),
s.s2.getPointer());
s.read();
assertEquals("Wrong memory for structure field 1 after read",
s.getPointer(), s.s1.getPointer());
assertEquals("Wrong memory for structure field 2 after read",
s.getPointer().share(s.s1.size()),
s.s2.getPointer());
}
public void testStructureByValueField() {
class TestStructure extends Structure {
public PublicTestStructure.ByValue s1, s2;
public int after;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("s1", "s2", "after");
}
}
TestStructure s = new TestStructure();
TestStructure s2 = new TestStructure();
assertNotNull("Inner structure should be initialized", s.s1);
assertNotNull("Inner structure should be initialized (cached)", s2.s1);
assertEquals("Wrong aggregate size",
s.s1.size() + s.s2.size() + 4, s.size());
s.write();
assertEquals("Wrong memory for structure field 1 after write",
s.getPointer(), s.s1.getPointer());
assertEquals("Wrong memory for structure field 2 after write",
s.getPointer().share(s.s1.size()),
s.s2.getPointer());
s.read();
assertEquals("Wrong memory for structure field 1 after read",
s.getPointer(), s.s1.getPointer());
assertEquals("Wrong memory for structure field 2 after read",
s.getPointer().share(s.s1.size()),
s.s2.getPointer());
}
public static class TestUnion extends Union {
public int u_int;
public float u_float;
public double u_double;
}
public void testUnionField() {
class TestStructure extends Structure {
public long s_long;
public TestUnion s_union;
public int s_int;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("s_long", "s_union", "s_int");
}
}
TestStructure s = new TestStructure();
assertEquals("Wrong structure size", Native.MAX_PADDING == 4 ? 20 : 24, s.size());
assertEquals("Wrong union size", 8, s.s_union.size());
}
public static class NonAllocatingTestStructure extends PublicTestStructure {
public NonAllocatingTestStructure() { }
public NonAllocatingTestStructure(Pointer p) { super(p); read(); }
@Override
protected void allocateMemory(int size) {
throw new Error("Memory unexpectedly allocated");
}
}
// TODO: add'l newInstance(Pointer) tests:
// NOTE: ensure structure-by-value respected (no more flag on newjavastructure)
// native call (direct mode)
// getNativeAlignment
public void testStructureFieldAvoidsSeparateMemoryAllocation() {
class TestStructure extends Structure {
public NonAllocatingTestStructure s1;
public TestStructure() { }
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("s1");
}
}
TestStructure ts = new TestStructure();
assertNotNull("Inner structure should be initialized", ts.s1);
}
public void testPrimitiveArrayField() {
class TestStructure extends Structure {
public byte[] buffer = new byte[1024];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("buffer");
}
}
TestStructure s = new TestStructure();
TestStructure s2 = new TestStructure();
assertEquals("Wrong size for structure with nested array", 1024, s.size());
assertEquals("Wrong size for structure with nested array (cached)", 1024, s2.size());
assertNotNull("Array should be initialized", s.buffer);
assertNotNull("Array should be initialized (cached)", s2.buffer);
s.write();
s.read();
}
public void testStructureArrayField() {
class TestStructure extends Structure {
// uninitialized array elements
public PublicTestStructure[] inner = new PublicTestStructure[2];
// initialized array elements
public PublicTestStructure[] inner2 = (PublicTestStructure[])
new PublicTestStructure().toArray(2);
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("inner", "inner2");
}
}
TestStructure s = new TestStructure();
int innerSize = new PublicTestStructure().size();
assertEquals("Wrong size for structure with nested array of struct",
s.inner.length * innerSize + s.inner2.length * innerSize,
s.size());
Structure s0 = s.inner2[0];
Structure s1 = s.inner2[1];
s.write();
assertNotNull("Inner array elements should auto-initialize after write", s.inner[0]);
assertSame("Inner array (2) element 0 reference should not be changed after write", s0, s.inner2[0]);
assertSame("Inner array (2) element 1 reference should not be changed after write", s1, s.inner2[1]);
s.inner[0].x = s.inner[1].x = -1;
s.inner2[0].x = s.inner2[1].x = -1;
s.read();
assertEquals("Inner structure array element 0 not properly read",
0, s.inner[0].x);
assertEquals("Inner structure array element 1 not properly read",
0, s.inner[1].x);
// First element (after toArray()) should preserve values from field initializers
assertEquals("Inner structure array (2) element 0 not properly read",
1, s.inner2[0].x);
// Subsequent elements from toArray() are initialized from first's
// memory, which is zeroed
assertEquals("Inner structure array (2) element 1 not properly read",
0, s.inner2[1].x);
assertEquals("Wrong memory for uninitialized nested array",
s.getPointer(), s.inner[0].getPointer());
assertEquals("Wrong memory for initialized nested array",
s.getPointer().share(innerSize * s.inner.length),
s.inner2[0].getPointer());
}
public static class ToArrayTestStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("inner");
public PublicTestStructure[] inner =
(PublicTestStructure[])new PublicTestStructure().toArray(2);
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testToArrayWithStructureArrayField() {
ToArrayTestStructure[] array =
(ToArrayTestStructure[])new ToArrayTestStructure().toArray(2);
assertEquals("Wrong address for top-level array element",
array[0].getPointer().share(array[0].size()),
array[1].getPointer());
assertEquals("Wrong address for nested array element",
array[1].inner[0].getPointer().share(array[1].inner[0].size()),
array[1].inner[1].getPointer());
}
public void testUninitializedNestedArrayFails() {
class TestStructure extends Structure {
public Pointer[] buffer;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("buffer");
}
}
Structure s = new TestStructure();
try {
s.size();
fail("Size can't be calculated unless array fields are initialized");
}
catch(IllegalStateException e) {
}
}
public void testReadWriteStructure() {
class TestStructure extends Structure {
public TestStructure() {
// Have to do this due to inline primitive arrays
allocateMemory();
}
public boolean z; // native int
public byte b; // native char
public char c; // native wchar_t
public short s; // native short
public int i; // native int
public long l; // native long long
public float f; // native float
public double d; // native double
public byte[] ba = new byte[3];
public char[] ca = new char[3];
public short[] sa = new short[3];
public int[] ia = new int[3];
public long[] la = new long[3];
public float[] fa = new float[3];
public double[] da = new double[3];
public PublicTestStructure nested;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("z", "b", "c", "s", "i", "l", "f", "d", "ba", "ca", "sa", "ia", "la", "fa", "da", "nested");
}
}
TestStructure s = new TestStructure();
// set content of the structure
s.z = true;
s.b = 1;
s.c = 2;
s.s = 3;
s.i = 4;
s.l = 5;
s.f = 6.0f;
s.d = 7.0;
s.nested.x = 1;
s.nested.y = 2;
for (int i = 0; i < 3; i++) {
s.ba[i] = (byte) (8 + i);
s.ca[i] = (char) (11 + i);
s.sa[i] = (short) (14 + i);
s.ia[i] = 17 + i;
s.la[i] = 23 + i;
s.fa[i] = (float) 26 + i;
s.da[i] = (double) 29 + i;
}
// write content to memory
s.write();
Pointer p = s.getPointer();
s = new TestStructure();
s.useMemory(p);
// read content from memory and compare field values
s.read();
assertEquals("Wrong boolean field value after write/read", s.z, true);
assertEquals("Wrong byte field value after write/read", s.b, 1);
assertEquals("Wrong char field value after write/read", s.c, 2);
assertEquals("Wrong short field value after write/read", s.s, 3);
assertEquals("Wrong int field value after write/read", s.i, 4);
assertEquals("Wrong long field value after write/read", s.l, 5);
assertEquals("Wrong float field value after write/read", s.f, 6.0f, 0f);
assertEquals("Wrong double field value after write/read", s.d, 7.0, 0d);
assertEquals("Wrong nested struct field value after write/read (x)", s.nested.x, 1);
assertEquals("Wrong nested struct field value after write/read (y)", s.nested.y, 2);
for (int i = 0; i < 3; i++) {
assertEquals("Wrong byte array field value after write/read", s.ba[i], (byte) (8 + i));
assertEquals("Wrong char array field value after write/read", s.ca[i], (char) (11 + i));
assertEquals("Wrong short array field value after write/read", s.sa[i], (short) (14 + i));
assertEquals("Wrong int array field value after write/read", s.ia[i], 17 + i);
assertEquals("Wrong long array field value after write/read", s.la[i], 23 + i);
assertEquals("Wrong float array field value after write/read", s.fa[i], (float) 26 + i, 0f);
assertEquals("Wrong double array field value after write/read", s.da[i], (double) 29 + i, 0d);
}
// test constancy of references after read
int[] ia = s.ia;
s.read();
assertTrue("Array field reference should be unchanged", ia == s.ia);
}
public void testNativeLongSize() throws Exception {
class TestStructure extends Structure {
public NativeLong l;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("l");
}
}
Structure s = new TestStructure();
assertEquals("Wrong size", NativeLong.SIZE, s.size());
}
public void testNativeLongRead() throws Exception {
class TestStructure extends Structure {
public int i;
public NativeLong l;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("i", "l");
}
}
TestStructure s = new TestStructure();
if (NativeLong.SIZE == 8) {
final long MAGIC = 0x1234567887654321L;
s.getPointer().setLong(8, MAGIC);
s.read();
assertEquals("NativeLong field mismatch", MAGIC, s.l.longValue());
}
else {
final int MAGIC = 0xABEDCF23;
s.getPointer().setInt(4, MAGIC);
s.read();
assertEquals("NativeLong field mismatch", MAGIC, s.l.intValue());
}
}
public void testNativeLongWrite() throws Exception {
class TestStructure extends Structure {
public int i;
public NativeLong l;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("i", "l");
}
}
TestStructure s = new TestStructure();
if (NativeLong.SIZE == 8) {
final long MAGIC = 0x1234567887654321L;
s.l = new NativeLong(MAGIC);
s.write();
long l = s.getPointer().getLong(8);
assertEquals("NativeLong field mismatch", MAGIC, l);
}
else {
final int MAGIC = 0xABEDCF23;
s.l = new NativeLong(MAGIC);
s.write();
int i = s.getPointer().getInt(4);
assertEquals("NativeLong field mismatch", MAGIC, i);
}
}
public void testMemoryField() {
class MemoryFieldStructure extends Structure {
public Memory m;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("m");
}
}
new MemoryFieldStructure().size();
}
public void testDisallowFunctionPointerAsField() {
class DisallowFunctionPointer extends Structure {
public Function cb;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("cb");
}
}
try {
new DisallowFunctionPointer().size();
fail("Function fields should not be allowed");
}
catch(IllegalArgumentException e) {
// expected - ignored
}
}
public static class BadFieldStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("badField");
public Object badField;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testUnsupportedField() {
class BadNestedStructure extends Structure {
public BadFieldStructure badStruct = new BadFieldStructure();
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("badStruct");
}
}
try {
new BadFieldStructure();
fail("Should throw IllegalArgumentException on bad field");
}
catch(IllegalArgumentException e) {
assertTrue("Exception should include field name: " + e.getMessage(), e.getMessage().indexOf("badField") != -1);
}
try {
new BadNestedStructure();
fail("Should throw IllegalArgumentException on bad field");
}
catch(IllegalArgumentException e) {
assertTrue("Exception should include enclosing type: " + e,
e.getMessage().indexOf(BadNestedStructure.class.getName()) != -1);
assertTrue("Exception should include nested field name: " + e,
e.getMessage().indexOf("badStruct") != -1);
assertTrue("Exception should include field name: " + e,
e.getMessage().indexOf("badField") != -1);
}
}
public void testToArray() {
final int allocated[] = { 0 };
PublicTestStructure.allocations = 0;
PublicTestStructure s = new PublicTestStructure();
PublicTestStructure[] array = (PublicTestStructure[])s.toArray(1);
assertEquals("Array should consist of a single element",
1, array.length);
assertEquals("First element should be original", s, array[0]);
array = (PublicTestStructure[])s.toArray(2);
assertEquals("Structure memory should be expanded", 2, array.length);
assertEquals("No memory should be allocated for new element", 1, PublicTestStructure.allocations);
assertEquals("Structure.read called on New element", 0, array[1].x);
}
public void testByReferenceArraySync() {
PublicTestStructure.ByReference s = new PublicTestStructure.ByReference();
PublicTestStructure.ByReference[] array =
(PublicTestStructure.ByReference[])s.toArray(2);
class TestStructure extends Structure {
public PublicTestStructure.ByReference ref;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("ref");
}
}
TestStructure ts = new TestStructure();
ts.ref = s;
final int VALUE = 42;
array[0].x = VALUE;
array[1].x = VALUE;
ts.write();
assertEquals("Array element not written: " + array[0],
VALUE, array[0].getPointer().getInt(0));
assertEquals("Array element not written: " + array[1],
VALUE, array[1].getPointer().getInt(0));
array[0].getPointer().setInt(4, VALUE);
array[1].getPointer().setInt(4, VALUE);
ts.read();
assertEquals("Array element not read: " + array[0], VALUE, array[0].y);
assertEquals("Array element not read: " + array[1], VALUE, array[1].y);
}
public static class CbStruct extends Structure {
public static final List<String> FIELDS = createFieldsOrder("cb");
public Callback cb;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testCallbackWrite() {
final CbStruct s = new CbStruct();
s.cb = new Callback() {
public void callback() {
}
};
s.write();
Pointer func = s.getPointer().getPointer(0);
assertNotNull("Callback trampoline not set", func);
Map<Callback, CallbackReference> refs = CallbackReference.callbackMap;
assertTrue("Callback not cached", refs.containsKey(s.cb));
CallbackReference ref = refs.get(s.cb);
assertEquals("Wrong trampoline", ref.getTrampoline(), func);
}
public void testUninitializedArrayField() {
class UninitializedArrayFieldStructure extends Structure {
public byte[] array;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("array");
}
}
try {
Structure s = new UninitializedArrayFieldStructure();
assertTrue("Invalid size: " + s.size(), s.size() > 0);
fail("Uninitialized array field should cause write failure");
} catch(IllegalStateException e) {
// expected
}
}
public static class StructureWithArrayOfStructureField extends Structure {
public static final List<String> FIELDS = createFieldsOrder("array");
public Structure[] array;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testPlainStructureArrayField() {
try {
new StructureWithArrayOfStructureField();
fail("Structure[] should not be allowed as a field of Structure");
}
catch(IllegalArgumentException e) {
// expected - ignored
}
catch(Exception e) {
fail("Wrong exception thrown when Structure[] field encountered in a Structure: " + e);
}
}
public static class ArrayOfPointerStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("array");
final static int SIZE = 10;
public Pointer[] array = new Pointer[SIZE];
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testPointerArrayField() {
ArrayOfPointerStructure s = new ArrayOfPointerStructure();
int size = s.size();
assertEquals("Wrong size", ArrayOfPointerStructure.SIZE * Native.POINTER_SIZE, size);
s.array[0] = s.getPointer();
s.write();
s.array[0] = null;
s.read();
assertEquals("Wrong first element", s.getPointer(), s.array[0]);
}
public static class VolatileStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("counter", "value");
public volatile int counter;
public int value;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testVolatileStructureField() {
VolatileStructure s = new VolatileStructure();
s.counter = 1;
s.value = 1;
s.write();
assertEquals("Volatile field should not be written", 0, s.getPointer().getInt(0));
assertEquals("Non-volatile field should be written", 1, s.getPointer().getInt(4));
s.writeField("counter");
assertEquals("Explicit volatile field write failed", 1, s.getPointer().getInt(0));
s.equals(s);
assertEquals("Structure equals should leave volatile field unchanged", 1, s.getPointer().getInt(0));
s.hashCode();
assertEquals("Structure equals should leave volatile field unchanged", 1, s.getPointer().getInt(0));
}
public static class StructureWithPointers extends Structure {
public static final List<String> FIELDS = createFieldsOrder("s1", "s2");
public PublicTestStructure.ByReference s1;
public PublicTestStructure.ByReference s2;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testStructureByReferenceField() {
StructureWithPointers s = new StructureWithPointers();
assertEquals("Wrong size for structure with structure references", Native.POINTER_SIZE * 2, s.size());
assertNull("Initial refs should be null", s.s1);
}
public void testRegenerateStructureByReferenceField() {
StructureWithPointers s = new StructureWithPointers();
PublicTestStructure.ByReference inner = new PublicTestStructure.ByReference();
PublicTestStructure.allocations = 0;
s.s1 = inner;
s.write();
s.s1 = null;
s.read();
assertEquals("Inner structure not regenerated on read", inner, s.s1);
assertEquals("Inner structure should not allocate memory", 0, PublicTestStructure.allocations);
}
public void testPreserveStructureByReferenceWithUnchangedPointerOnRead() {
StructureWithPointers s = new StructureWithPointers();
PublicTestStructure.ByReference inner =
new PublicTestStructure.ByReference();
s.s1 = inner;
s.write();
s.read();
assertSame("Read should preserve structure object", inner, s.s1);
assertTrue("Read should preserve structure memory",
inner.getPointer() instanceof Memory);
}
public static class TestPointer extends PointerType { }
public void testPreservePointerFields() {
class TestStructure extends Structure {
public Pointer p = new Memory(256);
public TestPointer p2 = new TestPointer() {
{ setPointer(new Memory(256)); }
};
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("p", "p2");
}
}
TestStructure s = new TestStructure();
final Pointer p = s.p;
final TestPointer p2 = s.p2;
s.write();
s.read();
assertSame("Should preserve Pointer references if peer unchanged", p, s.p);
assertSame("Should preserve PointerType references if peer unchanged", p2, s.p2);
}
public void testPreserveStringFields() {
final String VALUE = getName();
final WString WVALUE = new WString(getName() + UNICODE);
class TestStructure extends Structure {
public String s;
public WString ws;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("s", "ws");
}
}
TestStructure s = new TestStructure();
Memory m = new Memory(VALUE.length()+1);
m.setString(0, VALUE);
Memory m2 = new Memory((WVALUE.length()+1)*Native.WCHAR_SIZE);
m2.setString(0, WVALUE);
s.getPointer().setPointer(0, m);
s.getPointer().setPointer(Native.POINTER_SIZE, m2);
s.read();
assertEquals("Wrong String field value", VALUE, s.s);
assertEquals("Wrong WString field value", WVALUE, s.ws);
s.write();
assertEquals("String field should not be overwritten: " + s, m, s.getPointer().getPointer(0));
assertEquals("WString field should not be overwritten: " + s, m2, s.getPointer().getPointer(Native.POINTER_SIZE));
}
// Ensure string cacheing doesn't interfere with wrapped structure writes.
public static class StructureFromPointer extends Structure {
public static final List<String> FIELDS = createFieldsOrder("s", "ws");
public String s;
public WString ws;
public StructureFromPointer(Pointer p) {
super(p);
read();
}
public StructureFromPointer() {
super();
}
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testInitializeStructureFieldWithStrings() {
class ContainingStructure extends Structure {
public StructureFromPointer inner;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("inner");
}
}
StructureFromPointer o = new StructureFromPointer();
Charset charset = Charset.forName(o.getStringEncoding());
final String VALUE = getName() + charset.decode(charset.encode(UNICODE));
final WString WVALUE = new WString(VALUE);
o.s = VALUE;
o.ws = WVALUE;
o.write();
StructureFromPointer t = new StructureFromPointer(o.getPointer());
assertEquals("String field not initialized", VALUE, t.s);
assertEquals("WString field not initialized", WVALUE, t.ws);
ContainingStructure outer = new ContainingStructure();
outer.inner = t;
outer.write();
assertEquals("Inner String field corrupted", VALUE, outer.inner.s);
assertEquals("Inner WString field corrupted", WVALUE, outer.inner.ws);
outer.inner.read();
assertEquals("Native memory behind Inner String field not updated", VALUE, outer.inner.s);
assertEquals("Native memory behind Inner WString field not updated", WVALUE, outer.inner.ws);
}
public void testOverwriteStructureByReferenceFieldOnRead() {
StructureWithPointers s = new StructureWithPointers();
PublicTestStructure.ByReference inner =
new PublicTestStructure.ByReference();
PublicTestStructure.ByReference inner2 =
new PublicTestStructure.ByReference();
s.s1 = inner2;
s.write();
s.s1 = inner;
s.read();
assertNotSame("Read should overwrite structure reference", inner, s.s1);
}
public void testAutoWriteStructureByReferenceField() {
StructureWithPointers s = new StructureWithPointers();
s.s1 = new StructureTest.PublicTestStructure.ByReference();
s.s1.x = -1;
s.write();
assertEquals("Structure.ByReference field not written automatically",
-1, s.s1.getPointer().getInt(0));
}
public void testStructureByReferenceArrayField() {
class TestStructure extends Structure {
public PublicTestStructure.ByReference[] array = new PublicTestStructure.ByReference[2];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("array");
}
}
TestStructure s = new TestStructure();
assertEquals("Wrong structure size", 2*Native.POINTER_SIZE, s.size());
PublicTestStructure.ByReference ref = new PublicTestStructure.ByReference();
ref.x = 42;
Object aref = s.array;
s.array[0] = ref;
s.array[1] = new PublicTestStructure.ByReference();
s.write();
s.read();
assertSame("Array reference should not change", aref, s.array);
assertSame("Elements should not be overwritten when unchanged",
ref, s.array[0]);
s.array[0] = null;
s.read();
assertNotSame("Null should be overwritten with a new ref", ref, s.array[0]);
assertNotNull("New ref should not be null", s.array[0]);
assertEquals("New ref should be equivalent", ref, s.array[0]);
}
public void testAutoReadWriteStructureByReferenceArrayField() {
class TestStructure extends Structure {
public PublicTestStructure.ByReference field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
TestStructure s = new TestStructure();
s.field = new PublicTestStructure.ByReference();
PublicTestStructure.ByReference[] array =
(PublicTestStructure.ByReference[])s.field.toArray(2);
final int VALUE = -1;
array[1].x = VALUE;
s.write();
assertEquals("ByReference array member not auto-written",
VALUE, array[1].getPointer().getInt(0));
array[1].getPointer().setInt(0, VALUE*2);
s.read();
assertEquals("ByReference array member not auto-read",
VALUE*2, array[1].x);
}
public static class NestedTypeInfoStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("inner", "dummy");
public static class Inner extends Structure {
public static final List<String> FIELDS = createFieldsOrder("dummy");
public int dummy;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public Inner inner;
public int dummy;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public static class size_t extends IntegerType {
private static final long serialVersionUID = 1L;
public size_t() { this(0); }
public size_t(long value) { super(Native.POINTER_SIZE, value); }
}
/** Same structure as the internal representation, to be initialized from
* the internal FFIType native data.
*/
public static class TestFFIType extends Structure {
public static final List<String> FIELDS = createFieldsOrder("size", "alignment", "type", "elements");
// NOTE: this field is not normally initialized by libffi
// We force initialize by calling initialize_ffi_type
public size_t size;
public short alignment;
public short type;
public Pointer elements;
public TestFFIType(Pointer p) {
super(p);
read();
assertTrue("Test FFIType type not initialized: " + this, this.type != 0);
// Force libffi to explicitly calculate the size field of
// this FFIType object
int size = Native.initialize_ffi_type(p.peer);
read();
assertEquals("Test FFIType size improperly initialized: " + TestFFIType.this, size, TestFFIType.this.size.intValue());
}
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testNestedStructureTypeInfo() {
NestedTypeInfoStructure s = new NestedTypeInfoStructure();
Pointer p = s.getTypeInfo();
assertNotNull("Type info should not be null", p);
TestFFIType ffi_type = new TestFFIType(p);
assertEquals("FFIType size mismatch: " + ffi_type, s.size(), ffi_type.size.intValue());
Pointer els = ffi_type.elements;
Pointer inner = s.inner.getTypeInfo();
assertEquals("Wrong type information for 'inner' field",
inner, els.getPointer(0));
assertEquals("Wrong type information for integer field",
Structure.getTypeInfo(0).getPointer(),
els.getPointer(Native.POINTER_SIZE));
assertNull("Type element list should be null-terminated",
els.getPointer(Native.POINTER_SIZE*2));
}
public void testInnerArrayTypeInfo() {
class TestStructure extends Structure {
public int[] inner = new int[5];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("inner");
}
}
Structure s = new TestStructure();
Pointer p = s.getTypeInfo();
assertNotNull("Type info should not be null", p);
TestFFIType ffi_type = new TestFFIType(p);
assertEquals("Wrong structure size", 20, s.size());
assertEquals("FFIType info size mismatch", s.size(), ffi_type.size.intValue());
}
public void testTypeInfoForNull() {
assertEquals("Wrong type information for 'null'",
Structure.getTypeInfo(new Pointer(0)),
Structure.getTypeInfo(null));
}
public void testToString() {
// wce missing String.matches() and regex support
if (Platform.isWindowsCE()) return;
class TestStructure extends Structure {
public int intField;
public PublicTestStructure inner;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("intField", "inner");
}
}
TestStructure s = new TestStructure();
final String LS = System.lineSeparator();
System.setProperty("jna.dump_memory", "true");
final String EXPECTED = "(?m).*" + s.size() + " bytes.*\\{" + LS
+ " int intField@0x0=0x0000" + LS
+ " .* inner@0x4=.*\\{" + LS
+ " int x@0x0=.*" + LS
+ " int y@0x4=.*" + LS
+ " \\}" + LS
+ "\\}" + LS
+ "memory dump" + LS
+ "\\[[0-9a-f]+\\]" + LS
+ "\\[[0-9a-f]+\\]" + LS
+ "\\[[0-9a-f]+\\]";
String actual = s.toString();
assertTrue("Improperly formatted toString(): expected "
+ EXPECTED + "\n" + actual,
actual.matches(EXPECTED));
System.setProperty("jna.dump_memory", "false");
assertFalse("Doesn't dump memory when jna.dump_memory is false",
s.toString().contains("memory dump"));
}
public void testNativeMappedWrite() {
class TestStructure extends Structure {
public ByteByReference ref;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("ref");
}
}
TestStructure s = new TestStructure();
ByteByReference ref = s.ref = new ByteByReference();
s.write();
assertEquals("Value not properly written", ref.getPointer(), s.getPointer().getPointer(0));
s.ref = null;
s.write();
assertNull("Non-null value was written: " + s.getPointer().getPointer(0), s.getPointer().getPointer(0));
}
public void testNativeMappedRead() {
class TestStructure extends Structure {
public ByteByReference ref;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("ref");
}
}
TestStructure s = new TestStructure();
s.read();
assertNull("Should read null for initial field value", s.ref);
ByteByReference ref = new ByteByReference();
s.getPointer().setPointer(0, ref.getPointer());
s.read();
assertEquals("Field incorrectly read", ref, s.ref);
s.getPointer().setPointer(0, null);
s.read();
assertNull("Null field incorrectly read", s.ref);
}
public static class ROStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("field");
public final int field;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
{
// Initialize in ctor to avoid compiler replacing
// field references with a constant everywhere
field = 0;
}
}
private ROStructure avoidConstantFieldOptimization(ROStructure s) {
return s;
}
public void testReadOnlyField() {
if (!Platform.RO_FIELDS) {
try {
new ROStructure();
fail("Creation of a Structure with final fields should fail");
}
catch(Exception e) {
}
return;
}
ROStructure s = new ROStructure();
s.getPointer().setInt(0, 42);
s.read();
s = avoidConstantFieldOptimization(s);
assertEquals("Field value should be set from native", 42, s.field);
s.getPointer().setInt(0, 0);
s.read();
s = avoidConstantFieldOptimization(s);
assertEquals("Field value not synched after native change", 0, s.field);
// Read-only fields should not be copied to native memory
s.getPointer().setInt(0, 42);
try { s.write(); } catch(UnsupportedOperationException e) { }
assertEquals("Field should not be written", 42, s.getPointer().getInt(0));
// Native changes should propagate to read-only fields
s.read();
s = avoidConstantFieldOptimization(s);
assertEquals("Field value not synched after native change (2)", 42, s.field);
}
public void testNativeMappedArrayField() {
final int SIZE = 24;
class TestStructure extends Structure {
public NativeLong[] longs = new NativeLong[SIZE];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("longs");
}
}
TestStructure s = new TestStructure();
assertEquals("Wrong structure size", Native.LONG_SIZE * SIZE, s.size());
NativeLong[] aref = s.longs;
for (int i=0;i < s.longs.length;i++) {
s.longs[i] = new NativeLong(i);
}
s.write();
for (int i=0;i < s.longs.length;i++) {
assertEquals("Value not written to memory at index " + i,
i, s.getPointer().getNativeLong(i * NativeLong.SIZE).intValue());
}
s.read();
assertEquals("Array reference should remain unchanged on read",
aref, s.longs);
for (int i=0;i < s.longs.length;i++) {
assertEquals("Wrong value after read at index " + i,
i, s.longs[i].intValue());
}
}
public void testInitializeNativeMappedField() {
final long VALUE = 20;
final NativeLong INITIAL = new NativeLong(VALUE);
class TestStructure extends Structure {
// field overwritten, wrong value before write
// NL bug, wrong value written
{ setAlignType(ALIGN_NONE); }
public NativeLong nl = INITIAL;
public NativeLong uninitialized;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("nl", "uninitialized");
}
}
TestStructure ts = new TestStructure();
TestStructure ts2 = new TestStructure();
assertEquals("Wrong value in field", VALUE, ts.nl.longValue());
assertSame("Initial value overwritten", INITIAL, ts.nl);
assertEquals("Wrong field value before write", VALUE, ts.nl.longValue());
assertNotNull("Uninitialized field should be initialized", ts.uninitialized);
assertNotNull("Uninitialized field should be initialized (cached)", ts2.uninitialized);
assertEquals("Wrong initialized value", 0, ts.uninitialized.longValue());
ts.write();
assertEquals("Wrong field value written", VALUE, ts.getPointer().getNativeLong(0).longValue());
assertEquals("Wrong field value written (2)", 0, ts.getPointer().getNativeLong(NativeLong.SIZE).longValue());
ts.read();
assertEquals("Wrong field value", VALUE, ts.nl.longValue());
assertEquals("Wrong field value (2)", 0, ts.uninitialized.longValue());
}
public void testThrowErrorOnMissingFieldOrderOnDerivedStructure() {
class TestStructure extends Structure {
public int f1, f2;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("f1", "f2");
}
}
class NoFieldOrder extends TestStructure {
public int f3;
}
try {
new NoFieldOrder();
fail("Expected an error when structure fails to provide field order");
}
catch(Error e) {
}
}
public void testThrowErrorOnIncorrectFieldOrderNameMismatch() {
class TestStructure extends Structure {
public int f1, f2;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("F1", "F2");
}
}
try {
new TestStructure();
fail("Expected an error when creating a structure without mismatched field names");
}
catch(Error e) {
}
}
public void testThrowErrorOnIncorrectFieldOrderCount() {
class TestStructure extends Structure {
public int f1, f2;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("f1", "f2", "f3");
}
}
try {
new TestStructure();
fail("Expected an error when creating a structure with wrong number of fiels in getFieldOrder()");
}
catch(Error e) {
// expected - ignored
}
}
public static class XTestStructure extends Structure {
public static final List<String> FIELDS = createFieldsOrder("first");
public int first = 1;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public static class XTestStructureSub extends XTestStructure {
public static final List<String> EXTRA_FIELDS = createFieldsOrder("second");
private static final AtomicReference<List<String>> fieldsHolder = new AtomicReference<>(null);
private static List<String> resolveEffectiveFields(List<String> baseFields) {
List<String> fields;
synchronized (fieldsHolder) {
fields = fieldsHolder.get();
if (fields == null) {
fields = createFieldsOrder(baseFields, EXTRA_FIELDS);
fieldsHolder.set(fields);
}
}
return fields;
}
public int second = 2;
@Override
protected List<String> getFieldOrder() {
return resolveEffectiveFields(super.getFieldOrder());
}
}
public void testInheritedStructureFieldOrder() {
XTestStructureSub s = new XTestStructureSub();
assertEquals("Wrong size", 8, s.size());
s.write();
assertEquals("Wrong first field: " + s, s.first, s.getPointer().getInt(0));
assertEquals("Wrong second field: " + s, s.second, s.getPointer().getInt(4));
}
public void testVariedStructureFieldOrder() {
final String[] ORDER = new String[] { "one", "two", "three" };
final String[] ORDER2 = new String[] { "one", "two", "three", "four", "five" };
class TestStructure extends Structure {
public int one = 1;
public int three = 3;
public int two = 2;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList(ORDER);
}
}
class DerivedTestStructure extends TestStructure {
public int five = 5;
public int four = 4;
@Override
protected List<String> getFieldOrder() {
List<String> list = new ArrayList<>(super.getFieldOrder());
list.addAll(Arrays.asList("four", "five"));
return list;
}
}
TestStructure s = new TestStructure();
assertEquals("Wrong field order", Arrays.asList(ORDER), s.getFieldOrder());
s.write();
assertEquals("Wrong first field: " + s, s.one, s.getPointer().getInt(0));
assertEquals("Wrong second field: " + s, s.two, s.getPointer().getInt(4));
assertEquals("Wrong third field: " + s, s.three, s.getPointer().getInt(8));
DerivedTestStructure s2 = new DerivedTestStructure();
assertEquals("Wrong field order", Arrays.asList(ORDER2), s2.getFieldOrder());
s2.write();
assertEquals("Wrong first field: " + s2, s2.one, s2.getPointer().getInt(0));
assertEquals("Wrong second field: " + s2, s2.two, s2.getPointer().getInt(4));
assertEquals("Wrong third field: " + s2, s2.three, s2.getPointer().getInt(8));
assertEquals("Wrong derived field (1): " + s2, s2.four, s2.getPointer().getInt(12));
assertEquals("Wrong derived field (2): " + s2, s2.five, s2.getPointer().getInt(16));
}
public void testCustomTypeMapper() {
class TestField { }
final DefaultTypeMapper mapper = new DefaultTypeMapper() {
{
addTypeConverter(TestField.class, new TypeConverter() {
@Override
public Object fromNative(Object value, FromNativeContext context) {
return new TestField();
}
@Override
public Class<?> nativeType() {
return String.class;
}
@Override
public Object toNative(Object value, ToNativeContext ctx) {
return value == null ? null : value.toString();
}
});
}
};
class TestStructure extends Structure {
public TestField field;
public TestStructure() {
super(mapper);
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
Structure s = new TestStructure();
assertEquals("Wrong type mapper: " + s, mapper, s.getTypeMapper());
}
public void testWriteWithNullBoxedPrimitives() {
class TestStructure extends Structure {
public Boolean zfield;
public Integer field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("zfield", "field");
}
}
TestStructure s = new TestStructure();
s.write();
s.read();
assertNotNull("Field should not be null after read", s.field);
}
@SuppressWarnings("unlikely-arg-type")
public void testStructureEquals() {
class OtherStructure extends Structure {
public int first;
public int[] second = new int[4];
public Pointer[] third = new Pointer[4];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("first", "second", "third");
}
}
class TestStructure extends Structure {
public int first;
public int[] second = new int[4];
public Pointer[] third = new Pointer[4];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("first", "second", "third");
}
public TestStructure() { }
public TestStructure(Pointer p) { super(p); }
}
OtherStructure s0 = new OtherStructure();
TestStructure s1 = new TestStructure();
TestStructure s2 = new TestStructure(s1.getPointer());
TestStructure s3 = new TestStructure(s2.getPointer());
TestStructure s4 = new TestStructure();
assertFalse("Structures of different classes with same fields are not equal", s1.equals(s0));
assertFalse("Structures of different classes with same fields are not equal (reflexive)", s0.equals(s1));
assertFalse("Compare to null failed", s1.equals(null));
assertTrue("Equals is not reflexive", s1.equals(s1));
assertTrue("Equals failed on structures with same pointer", s1.equals(s2));
assertTrue("Equals is not symmetric", s2.equals(s1));
assertTrue("Equals is not transitive", s1.equals(s2) && s2.equals(s3) && s1.equals(s3));
assertFalse("Compare to different structure failed", s1.equals(s4));
}
public void testStructureHashCodeMatchesWhenEqual() {
class TestStructure extends Structure {
public int first;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("first");
}
}
TestStructure s1 = new TestStructure();
TestStructure s2 = new TestStructure();
assertFalse("hashCode should be different for two different structures", s1.hashCode() == s2.hashCode());
s2.useMemory(s1.getPointer());
assertEquals("hashCode should match when structures have same pointer", s1.hashCode(), s2.hashCode());
s2.useMemory(s1.getPointer());
assertEquals("hashCode should match when structures have same pointer", s1.hashCode(), s2.hashCode());
}
public void testRecursiveWrite() {
class TestStructureByRef extends Structure implements Structure.ByReference{
public TestStructureByRef(Pointer p) { super(p); }
public TestStructureByRef() { }
public int unique;
public TestStructureByRef s;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("unique", "s");
}
}
TestStructureByRef s = new TestStructureByRef();
s.s = new TestStructureByRef();
s.unique = 1;
s.s.s = s;
s.s.unique = 2;
s.write();
assertEquals("Structure field contents not written", 1, s.getPointer().getInt(0));
assertEquals("ByReference structure field contents not written", 2, s.s.getPointer().getInt(0));
s.s.unique = 0;
Structure value = s.s;
s.read();
assertEquals("ByReference structure field not preserved", value, s.s);
assertEquals("ByReference structure field contents not read", 2, s.s.unique);
assertTrue("Temporary storage should be cleared", Structure.busy().isEmpty());
}
public static class CyclicTestStructure extends Structure {
public static class ByReference extends CyclicTestStructure implements Structure.ByReference {}
public static final List<String> FIELDS = createFieldsOrder("next");
public CyclicTestStructure(Pointer p) { super(p); }
public CyclicTestStructure() { }
public CyclicTestStructure.ByReference next;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
}
public void testCyclicRead() {
CyclicTestStructure s = new CyclicTestStructure();
s.next = new CyclicTestStructure.ByReference();
Structure value = s.next;
s.next.next = s.next;
s.write();
s.read();
assertEquals("ByReference structure field not preserved", value, s.next);
value = s.next;
s.next.next = null;
s.read();
assertSame("ByReference structure field should reuse existing value", value, s.next);
assertSame("Nested ByReference structure field should reuse existing value", value, s.next.next);
}
public void testAvoidMemoryAllocationInPointerCTOR() {
class TestStructure extends Structure {
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
public TestStructure(Pointer p) {
super(p);
}
@Override
protected Memory autoAllocate(int size) {
fail("Memory should not be auto-allocated");
return null;
}
}
Memory p = new Memory(4);
Structure s = new TestStructure(p);
}
public void testPointerCTORWithInitializedFields() {
class TestStructure extends Structure {
public int intField;
public byte[] arrayField = new byte[256];
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("intField", "arrayField");
}
public TestStructure(Pointer p) {
super(p);
read(); // Important!
}
}
Memory p = new Memory(260);
p.setInt(0, 1);
p.setByte(4, (byte)2);
p.setByte(5, (byte)3);
p.setByte(6, (byte)4);
p.setByte(7, (byte)5);
TestStructure s = new TestStructure(p);
assertEquals("Structure primitive field not initialized",
(byte)1, s.intField);
assertEquals("Structure primitive array field not initialized",
(byte)2, s.arrayField[0]);
assertEquals("Structure primitive array field not initialized",
(byte)3, s.arrayField[1]);
assertEquals("Structure primitive array field not initialized",
(byte)4, s.arrayField[2]);
assertEquals("Structure primitive array field not initialized",
(byte)5, s.arrayField[3]);
assertEquals("Wrong structure size", p.size(), s.size());
}
public static class TestByReferenceArrayField extends Structure {
public static final List<String> FIELDS = createFieldsOrder("value1", "array", "value2");
public TestByReferenceArrayField() { }
public TestByReferenceArrayField(Pointer m) {
super(m);
read(); // Important!
}
public int value1;
public ByReference[] array = new ByReference[13];
public int value2;
@Override
protected List<String> getFieldOrder() {
return FIELDS;
}
public static class ByReference extends TestByReferenceArrayField implements Structure.ByReference { }
}
public static void testByReferenceArrayField() {
TestByReferenceArrayField.ByReference s = new TestByReferenceArrayField.ByReference();
s.value1 = 22;
s.array[0] = s;
s.value2 = 42;
s.write();
TestByReferenceArrayField s2 =
new TestByReferenceArrayField(s.getPointer());
assertEquals("value1 not properly read from Pointer", s.value1, s2.value1);
assertNotNull("Structure.ByReference array field was not initialized", s2.array);
assertEquals("Structure.ByReference array field initialized to incorrect length", 13, s2.array.length);
assertNotNull("Structure.ByReference array field element was not initialized", s2.array[0]);
assertEquals("Incorrect value for Structure.ByReference array field element", s.array[0].getPointer(), s2.array[0].getPointer());
assertEquals("Field 'value2' not properly read from Pointer", s.value2, s2.value2);
}
public void testEquals() {
class TestStructure extends Structure {
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
public TestStructure() { }
public TestStructure(Pointer p) { super(p); read(); }
}
Structure s = new TestStructure();
assertTrue("Should match self", s.equals(s));
assertFalse("Not equal null", s.equals(null));
assertFalse("Not equal some other object", s.equals(new Object()));
Structure s1 = new TestStructure(s.getPointer());
assertEquals("Same base address/type should be equal", s, s1);
}
public void testStructureLayoutCacheing() {
class TestStructure extends Structure {
public int field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
Structure ts = new TestStructure(); ts.ensureAllocated();
Structure ts2 = new TestStructure(); ts2.ensureAllocated();
assertSame("Structure layout not cached", ts.fields(), ts2.fields());
}
public void testStructureLayoutVariableNoCache() {
class TestStructure extends Structure {
public byte[] variable;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("variable");
}
public TestStructure(int size) {
this.variable = new byte[size];
}
}
Structure ts = new TestStructure(8);
Structure ts2 = new TestStructure(16);
// Ensure allocated; primitive array prevents initial layout calculation
ts.ensureAllocated(); ts2.ensureAllocated();
assertNotSame("Structure layout should not be cached", ts.fields(), ts2.fields());
}
public void testStructureLayoutCacheingWithTypeMapper() {
class TestTypeMapper extends DefaultTypeMapper {
{
TypeConverter tc = new TypeConverter() {
@Override
public Class<?> nativeType() { return int.class; }
@Override
public Object fromNative(Object nativeValue, FromNativeContext c) {
return Boolean.valueOf(nativeValue.equals(Integer.valueOf(0)));
}
@Override
public Object toNative(Object value, ToNativeContext c) {
return Integer.valueOf(Boolean.TRUE.equals(value) ? -1 : 0);
}
};
addTypeConverter(boolean.class, tc);
addTypeConverter(Boolean.class, tc);
}
}
final TestTypeMapper m = new TestTypeMapper();
class TestStructure extends Structure {
public boolean field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
public TestStructure() {
super(m);
}
public TestStructure(TypeMapper m) {
super(m);
}
}
Structure ts = new TestStructure();
Structure ts2 = new TestStructure();
Structure ts3 = new TestStructure(m);
assertSame("Structure layout should be cached with custom type mapper", ts.fields(), ts2.fields());
assertSame("Structure layout should be cached with custom type mapper, regardless of constructor type", ts.fields(), ts3.fields());
}
public void testStructureLayoutCacheingWithAlignment() {
class TestStructure extends Structure {
public byte first;
public int second;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("first", "second");
}
public TestStructure() {
setAlignType(ALIGN_NONE);
}
public TestStructure(int alignType) {
super(alignType);
}
}
Structure ts = new TestStructure();
Structure ts2 = new TestStructure();
Structure ts3 = new TestStructure(Structure.ALIGN_NONE);
assertSame("Structure layout should be cached with custom alignment", ts.fields(), ts2.fields());
assertSame("Structure layout should be cached with custom alignment, regardless of how set", ts.fields(), ts3.fields());
}
public void testStructureSetIterator() {
assertNotNull("Indirect test of StructureSet.Iterator",
Structure.busy().toString());
}
public void testFFITypeCalculationWithTypeMappedFields() {
final TypeMapper mapper = new TypeMapper() {
@Override
public FromNativeConverter getFromNativeConverter(Class<?> cls) {
if (Boolean.class.equals(cls)
|| boolean.class.equals(cls)) {
return new FromNativeConverter() {
@Override
public Class<?> nativeType() {
return byte.class;
}
@Override
public Object fromNative(Object nativeValue, FromNativeContext context) {
return nativeValue.equals(Byte.valueOf((byte)0))
? Boolean.FALSE : Boolean.TRUE;
}
};
}
return null;
}
@Override
public ToNativeConverter getToNativeConverter(Class<?> javaType) {
if (Boolean.class.equals(javaType)
|| boolean.class.equals(javaType)) {
return new ToNativeConverter() {
@Override
public Object toNative(Object value, ToNativeContext context) {
return Byte.valueOf(Boolean.TRUE.equals(value) ? (byte)1 : (byte)0);
}
@Override
public Class<?> nativeType() {
return byte.class;
}
};
}
return null;
}
};
class TestStructure extends Structure {
public boolean b;
public short s;
// Ensure we're not stuffed into a register
public int p0,p1,p2,p3,p4,p5,p6,p7;
public TestStructure() {
super(mapper);
}
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("b", "s", "p0", "p1", "p2", "p3", "p4", "p5", "p6", "p7");
}
}
Structure s = new TestStructure();
assertEquals("Wrong type mapper for structure", mapper, s.getTypeMapper());
TestFFIType ffi_type = new TestFFIType(Structure.getTypeInfo(s).getPointer());
assertEquals("Java Structure size does not match FFIType size",
s.size(), ffi_type.size.intValue());
}
public void testDefaultStringEncoding() {
class TestStructure extends Structure {
public String field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
TestStructure s = new TestStructure();
assertEquals("Wrong default structure encoding",
Native.getDefaultStringEncoding(),
s.getStringEncoding());
}
public void testStringFieldEncoding() throws Exception {
class TestStructure extends Structure {
public String field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
TestStructure s = new TestStructure();
final String ENCODING = "utf8";
s.setStringEncoding(ENCODING);
assertEquals("Manual customization of string encoding failed", ENCODING, s.getStringEncoding());
final String VALUE = "\u0444\u043b\u0441\u0432\u0443";
s.field = VALUE;
s.write();
byte[] expected = VALUE.getBytes("utf8");
byte[] actual = s.getPointer().getPointer(0).getByteArray(0, expected.length);
for (int i=0;i < Math.min(expected.length, actual.length);i++) {
assertEquals("Improperly encoded (" + ENCODING
+ ") on structure write at " + i,
expected[i], actual[i]);
}
assertEquals("Encoding length mismatch", expected.length, actual.length);
s.field = null;
s.read();
assertEquals("String not decoded properly on read", VALUE, s.field);
}
public void testThreadLocalSetReleasesReferences() {
class TestStructure extends Structure {
public String field;
@Override
protected List<String> getFieldOrder() {
return Arrays.asList("field");
}
}
TestStructure ts1 = new TestStructure();
TestStructure ts2 = new TestStructure();
StructureSet structureSet = (StructureSet) Structure.busy();
structureSet.add(ts1);
structureSet.add(ts2);
structureSet.remove(ts1);
assertNotNull(structureSet.elements[0]);
structureSet.remove(ts2);
assertNull(structureSet.elements[0]);
}
}
|