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 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
|
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*=============================================================================
**
** Class: Marshal
**
**
** Purpose: This class contains methods that are mainly used to marshal
** between unmanaged and managed types.
**
**
=============================================================================*/
namespace System.Runtime.InteropServices
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Win32Native = Microsoft.Win32.Win32Native;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.ComTypes;
[Serializable]
public enum CustomQueryInterfaceMode
{
Ignore = 0,
Allow = 1
}
//========================================================================
// All public methods, including PInvoke, are protected with linkchecks.
// Remove the default demands for all PInvoke methods with this global
// declaration on the class.
//========================================================================
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public static partial class Marshal
{
//====================================================================
// Defines used inside the Marshal class.
//====================================================================
private const int LMEM_FIXED = 0;
#if !FEATURE_PAL
private const int LMEM_MOVEABLE = 2;
private const long HIWORDMASK = unchecked((long)0xffffffffffff0000L);
#endif //!FEATURE_PAL
#if FEATURE_COMINTEROP
private static Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
#endif //FEATURE_COMINTEROP
// Win32 has the concept of Atoms, where a pointer can either be a pointer
// or an int. If it's less than 64K, this is guaranteed to NOT be a
// pointer since the bottom 64K bytes are reserved in a process' page table.
// We should be careful about deallocating this stuff. Extracted to
// a function to avoid C# problems with lack of support for IntPtr.
// We have 2 of these methods for slightly different semantics for NULL.
private static bool IsWin32Atom(IntPtr ptr)
{
#if FEATURE_PAL
return false;
#else
long lPtr = (long)ptr;
return 0 == (lPtr & HIWORDMASK);
#endif
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static bool IsNotWin32Atom(IntPtr ptr)
{
#if FEATURE_PAL
return false;
#else
long lPtr = (long)ptr;
return 0 != (lPtr & HIWORDMASK);
#endif
}
//====================================================================
// The default character size for the system. This is always 2 because
// the framework only runs on UTF-16 systems.
//====================================================================
public static readonly int SystemDefaultCharSize = 2;
//====================================================================
// The max DBCS character size for the system.
//====================================================================
public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize();
//====================================================================
// The name, title and description of the assembly that will contain
// the dynamically generated interop types.
//====================================================================
private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes";
private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types";
private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's";
private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes";
//====================================================================
// Helper method to retrieve the system's maximum DBCS character size.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetSystemMaxDBCSCharSize();
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
return null;
}
else if (IsWin32Atom(ptr)) {
return null;
}
else {
int nb = Win32Native.lstrlenA(ptr);
if( nb == 0) {
return string.Empty;
}
else {
return new String((sbyte *)ptr);
}
}
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringAnsi(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (len < 0)
throw new ArgumentException("len");
return new String((sbyte *)ptr, 0, len);
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr, int len)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (len < 0)
throw new ArgumentException("len");
return new String((char *)ptr, 0, len);
}
[System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static String PtrToStringUni(IntPtr ptr)
{
if (IntPtr.Zero == ptr) {
return null;
}
else if (IsWin32Atom(ptr)) {
return null;
}
else {
return new String((char *)ptr);
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr);
}
//====================================================================
// SizeOf()
//====================================================================
[ResourceExposure(ResourceScope.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException("structure");
// we never had a check for generics here
Contract.EndContractBlock();
return SizeOfHelper(structure.GetType(), true);
}
public static int SizeOf<T>(T structure)
{
return SizeOf((object)structure);
}
[ResourceExposure(ResourceScope.None)]
[Pure]
public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException("t");
if (!(t is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
Contract.EndContractBlock();
return SizeOfHelper(t, true);
}
public static int SizeOf<T>()
{
return SizeOf(typeof(T));
}
#if !FEATURE_CORECLR || FEATURE_CORESYSTEM
/// <summary>
/// Returns the aligned size of an instance of a value type.
/// </summary>
/// <typeparam name="T">Provide a value type to figure out its size</typeparam>
/// <returns>The aligned size of T in bytes.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static uint AlignedSizeOf<T>() where T : struct
{
uint size = SizeOfType(typeof(T));
if (size == 1 || size == 2)
{
return size;
}
if (IntPtr.Size == 8 && size == 4)
{
return size;
}
return AlignedSizeOfType(typeof(T));
}
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern uint SizeOfType(Type type);
// Type must be a value type with no object reference fields. We only
// assert this, due to the lack of a suitable generic constraint.
[MethodImpl(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern uint AlignedSizeOfType(Type type);
#endif // !FEATURE_CORECLR || FEATURE_CORESYSTEM
#if !FEATURE_CORECLR // Marshal is critical in CoreCLR, so SafeCritical members trigger Annotator violations
[System.Security.SecuritySafeCritical]
#endif // !FEATURE_CORECLR
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);
//====================================================================
// OffsetOf()
//====================================================================
public static IntPtr OffsetOf(Type t, String fieldName)
{
if (t == null)
throw new ArgumentNullException("t");
Contract.EndContractBlock();
FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f == null)
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), "fieldName");
RtFieldInfo rtField = f as RtFieldInfo;
if (rtField == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), "fieldName");
return OffsetOfHelper(rtField);
}
public static IntPtr OffsetOf<T>(string fieldName)
{
return OffsetOf(typeof(T), fieldName);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f);
//====================================================================
// UnsafeAddrOfPinnedArrayElement()
//
// IMPORTANT NOTICE: This method does not do any verification on the
// array. It must be used with EXTREME CAUTION since passing in
// an array that is not pinned or in the fixed heap can cause
// unexpected results !
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index);
[System.Security.SecurityCritical]
public static IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index)
{
return UnsafeAddrOfPinnedArrayElement((Array)arr, index);
}
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(byte[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CopyToNative(Object source, int startIndex, IntPtr destination, int length);
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CopyToManaged(IntPtr source, Object destination, int startIndex, int length);
//====================================================================
// Read from memory
//====================================================================
[DllImport(Win32Native.SHIM, EntryPoint="ND_RU1")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
return *addr;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static byte ReadByte(IntPtr ptr)
{
return ReadByte(ptr,0);
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI2")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
return *((short *)addr);
}
else
{
// unaligned read
short val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static short ReadInt16(IntPtr ptr)
{
return ReadInt16(ptr, 0);
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI4"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
return *((int *)addr);
}
else
{
// unaligned read
int val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int ReadInt32(IntPtr ptr)
{
return ReadInt32(ptr,0);
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, ofs);
#else
return (IntPtr) ReadInt64(ptr, ofs);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, ofs);
#else
return (IntPtr) ReadInt64(ptr, ofs);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static IntPtr ReadIntPtr(IntPtr ptr)
{
#if WIN32
return (IntPtr) ReadInt32(ptr, 0);
#else
return (IntPtr) ReadInt64(ptr, 0);
#endif
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_RI8"), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
return *((long *)addr);
}
else
{
// unaligned read
long val;
byte *valPtr = (byte *)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
valPtr[3] = addr[3];
valPtr[4] = addr[4];
valPtr[5] = addr[5];
valPtr[6] = addr[6];
valPtr[7] = addr[7];
return val;
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static long ReadInt64(IntPtr ptr)
{
return ReadInt64(ptr,0);
}
//====================================================================
// Write to memory
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteByte(IntPtr ptr, int ofs, byte val)
{
try
{
byte *addr = (byte *)ptr + ofs;
*addr = val;
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WU1")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
*((short *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI2")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
*((int *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI4")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt32(IntPtr ptr, int val)
{
WriteInt32(ptr,0,val);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
{
#if WIN32
WriteInt32(ptr, ofs, (int)val);
#else
WriteInt64(ptr, ofs, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
#if WIN32
WriteInt32(ptr, 0, (int)val);
#else
WriteInt64(ptr, 0, (long)val);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
{
byte *addr = (byte *)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
*((long *)addr) = val;
}
else
{
// unaligned write
byte *valPtr = (byte *)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
addr[3] = valPtr[3];
addr[4] = valPtr[4];
addr[5] = valPtr[5];
addr[6] = valPtr[6];
addr[7] = valPtr[7];
}
}
catch (NullReferenceException)
{
// this method is documented to throw AccessViolationException on any AV
throw new AccessViolationException();
}
}
[DllImport(Win32Native.SHIM, EntryPoint="ND_WI8")]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
public static extern void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val);
[System.Security.SecurityCritical] // auto-generated_required
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
}
//====================================================================
// GetLastWin32Error
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int GetLastWin32Error();
//====================================================================
// SetLastWin32Error
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern void SetLastWin32Error(int error);
//====================================================================
// GetHRForLastWin32Error
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static int GetHRForLastWin32Error()
{
int dwLastError = GetLastWin32Error();
if ((dwLastError & 0x80000000) == 0x80000000)
return dwLastError;
else
return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000);
}
//====================================================================
// Prelink
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void Prelink(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
InternalPrelink(rmi);
}
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[SecurityCritical]
private static extern void InternalPrelink(IRuntimeMethodInfo m);
[System.Security.SecurityCritical] // auto-generated_required
public static void PrelinkAll(Type c)
{
if (c == null)
throw new ArgumentNullException("c");
Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
if (mi != null)
{
for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
}
//====================================================================
// NumParamBytes
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static int NumParamBytes(MethodInfo m)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
if (rmi == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
return InternalNumParamBytes(rmi);
}
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
[SecurityCritical]
private static extern int InternalNumParamBytes(IRuntimeMethodInfo m);
//====================================================================
// Win32 Exception stuff
// These are mostly interesting for Structured exception handling,
// but need to be exposed for all exceptions (not just SEHException).
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern /* struct _EXCEPTION_POINTERS* */ IntPtr GetExceptionPointers();
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
//====================================================================
// Marshals data from a structure class to a native memory block.
// If the structure contains pointers to allocated blocks and
// "fDeleteOld" is true, this routine will call DestroyStructure() first.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld);
[System.Security.SecurityCritical]
public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld)
{
StructureToPtr((object)structure, ptr, fDeleteOld);
}
//====================================================================
// Marshals data from a native memory block to a preallocated structure class.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure(IntPtr ptr, Object structure)
{
PtrToStructureHelper(ptr, structure, false);
}
[System.Security.SecurityCritical]
public static void PtrToStructure<T>(IntPtr ptr, T structure)
{
PtrToStructure(ptr, (object)structure);
}
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(true)]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
if (ptr == IntPtr.Zero) return null;
if (structureType == null)
throw new ArgumentNullException("structureType");
if (structureType.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "structureType");
RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
PtrToStructureHelper(ptr, structure, true);
return structure;
}
[System.Security.SecurityCritical]
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)PtrToStructure(ptr, typeof(T));
}
//====================================================================
// Helper function to copy a pointer into a preallocated structure.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void PtrToStructureHelper(IntPtr ptr, Object structure, bool allowValueClasses);
//====================================================================
// Freeds all substructures pointed to by the native memory block.
// "structureclass" is used to provide layout information.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[System.Runtime.InteropServices.ComVisible(true)]
public static extern void DestroyStructure(IntPtr ptr, Type structuretype);
[System.Security.SecurityCritical]
public static void DestroyStructure<T>(IntPtr ptr)
{
DestroyStructure(ptr, typeof(T));
}
//====================================================================
// Returns the HInstance for this module. Returns -1 if the module
// doesn't have an HInstance. In Memory (Dynamic) Modules won't have
// an HInstance.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IntPtr GetHINSTANCE(Module m)
{
if (m == null)
throw new ArgumentNullException("m");
Contract.EndContractBlock();
RuntimeModule rtModule = m as RuntimeModule;
if (rtModule == null)
{
ModuleBuilder mb = m as ModuleBuilder;
if (mb != null)
rtModule = mb.InternalModule;
}
if (rtModule == null)
throw new ArgumentNullException(Environment.GetResourceString("Argument_MustBeRuntimeModule"));
return GetHINSTANCE(rtModule.GetNativeHandle());
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private extern static IntPtr GetHINSTANCE(RuntimeModule m);
//====================================================================
// Throws a CLR exception based on the HRESULT.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void ThrowExceptionForHR(int errorCode)
{
if (errorCode < 0)
ThrowExceptionForHRInternal(errorCode, IntPtr.Zero);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
ThrowExceptionForHRInternal(errorCode, errorInfo);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ThrowExceptionForHRInternal(int errorCode, IntPtr errorInfo);
//====================================================================
// Converts the HRESULT to a CLR exception.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Exception GetExceptionForHR(int errorCode)
{
if (errorCode < 0)
return GetExceptionForHRInternal(errorCode, IntPtr.Zero);
else
return null;
}
[System.Security.SecurityCritical] // auto-generated_required
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
return GetExceptionForHRInternal(errorCode, errorInfo);
else
return null;
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo);
//====================================================================
// Converts the CLR exception to an HRESULT. This function also sets
// up an IErrorInfo for the exception.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetHRForException(Exception e);
//====================================================================
// Converts the CLR exception to an HRESULT. This function also sets
// up an IErrorInfo for the exception.
// This function is only used in WinRT and converts ObjectDisposedException
// to RO_E_CLOSED
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetHRForException_WinRT(Exception e);
#if !FEATURE_PAL
//====================================================================
// This method is intended for compiler code generators rather
// than applications.
//====================================================================
//
[System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetUnmanagedThunkForManagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr GetUnmanagedThunkForManagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
//====================================================================
// This method is intended for compiler code generators rather
// than applications.
//====================================================================
//
[System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetManagedThunkForUnmanagedMethodPtr method has been deprecated and will be removed in a future release.", false)]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr GetManagedThunkForUnmanagedMethodPtr(IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature);
//====================================================================
// The hosting APIs allow a sophisticated host to schedule fibers
// onto OS threads, so long as they notify the runtime of this
// activity. A fiber cookie can be redeemed for its managed Thread
// object by calling the following service.
//====================================================================
//
[System.Security.SecurityCritical] // auto-generated_required
[ObsoleteAttribute("The GetThreadFromFiberCookie method has been deprecated. Use the hosting API to perform this operation.", false)]
public static Thread GetThreadFromFiberCookie(int cookie)
{
if (cookie == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_ArgumentZero"), "cookie");
Contract.EndContractBlock();
return InternalGetThreadFromFiberCookie(cookie);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Thread InternalGetThreadFromFiberCookie(int cookie);
#endif //!FEATURE_PAL
//====================================================================
// Memory allocation and deallocation.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(IntPtr cb)
{
// For backwards compatibility on 32 bit platforms, ensure we pass values between
// Int32.MaxValue and UInt32.MaxValue to Windows. If the binary has had the
// LARGEADDRESSAWARE bit set in the PE header, it may get 3 or 4 GB of user mode
// address space. It is remotely that those allocations could have succeeded,
// though I couldn't reproduce that. In either case, that means we should continue
// throwing an OOM instead of an ArgumentOutOfRangeException for "negative" amounts of memory.
UIntPtr numBytes;
#if WIN32
numBytes = new UIntPtr(unchecked((uint)cb.ToInt32()));
#else
numBytes = new UIntPtr(unchecked((ulong)cb.ToInt64()));
#endif
IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes));
if (pNewMem == IntPtr.Zero) {
throw new OutOfMemoryException();
}
return pNewMem;
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static IntPtr AllocHGlobal(int cb)
{
return AllocHGlobal((IntPtr)cb);
}
[System.Security.SecurityCritical] // auto-generated_required
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static void FreeHGlobal(IntPtr hglobal)
{
if (IsNotWin32Atom(hglobal)) {
if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) {
ThrowExceptionForHR(GetHRForLastWin32Error());
}
}
}
#if !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
if (pNewMem == IntPtr.Zero) {
throw new OutOfMemoryException();
}
return pNewMem;
}
//====================================================================
// String convertions.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToHGlobalAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException("s");
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
s.ConvertToAnsi((byte *)hglobal, nb, false, false);
return hglobal;
}
}
}
#endif // !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToHGlobalUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException("s");
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
fixed (char* firstChar = s)
{
String.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
}
}
#if !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToHGlobalAuto(String s)
{
// Ansi platforms are no longer supported
return StringToHGlobalUni(s);
}
#endif //!FEATURE_PAL
#if FEATURE_COMINTEROP
internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
//====================================================================
// Given a managed object that wraps a UCOMITypeLib, return its name
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibName(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static String GetTypeLibName(UCOMITypeLib pTLB)
{
return GetTypeLibName((ITypeLib)pTLB);
}
//====================================================================
// Given a managed object that wraps an ITypeLib, return its name
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static String GetTypeLibName(ITypeLib typelib)
{
if (typelib == null)
throw new ArgumentNullException("typelib");
Contract.EndContractBlock();
String strTypeLibName = null;
String strDocString = null;
int dwHelpContext = 0;
String strHelpFile = null;
typelib.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
return strTypeLibName;
}
//====================================================================
// Internal version of GetTypeLibName
// Support GUID_ManagedName which aligns with TlbImp
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
internal static String GetTypeLibNameInternal(ITypeLib typelib)
{
if (typelib == null)
throw new ArgumentNullException("typelib");
Contract.EndContractBlock();
// Try GUID_ManagedName first
ITypeLib2 typeLib2 = typelib as ITypeLib2;
if (typeLib2 != null)
{
Guid guid = ManagedNameGuid;
object val;
try
{
typeLib2.GetCustData(ref guid, out val);
}
catch(Exception)
{
val = null;
}
if (val != null && val.GetType() == typeof(string))
{
string customManagedNamespace = (string)val;
customManagedNamespace = customManagedNamespace.Trim();
if (customManagedNamespace.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase))
customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
else if (customManagedNamespace.EndsWith(".EXE", StringComparison.OrdinalIgnoreCase))
customManagedNamespace = customManagedNamespace.Substring(0, customManagedNamespace.Length - 4);
return customManagedNamespace;
}
}
return GetTypeLibName(typelib);
}
//====================================================================
// Given an managed object that wraps an UCOMITypeLib, return its guid
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibGuid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static Guid GetTypeLibGuid(UCOMITypeLib pTLB)
{
return GetTypeLibGuid((ITypeLib)pTLB);
}
//====================================================================
// Given an managed object that wraps an ITypeLib, return its guid
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Guid GetTypeLibGuid(ITypeLib typelib)
{
Guid result = new Guid ();
FCallGetTypeLibGuid (ref result, typelib);
return result;
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallGetTypeLibGuid(ref Guid result, ITypeLib pTLB);
//====================================================================
// Given a managed object that wraps a UCOMITypeLib, return its lcid
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeLibLcid(ITypeLib pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static int GetTypeLibLcid(UCOMITypeLib pTLB)
{
return GetTypeLibLcid((ITypeLib)pTLB);
}
//====================================================================
// Given a managed object that wraps an ITypeLib, return its lcid
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetTypeLibLcid(ITypeLib typelib);
//====================================================================
// Given a managed object that wraps an ITypeLib, return it's
// version information.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetTypeLibVersion(ITypeLib typeLibrary, out int major, out int minor);
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its guid.
//====================================================================
[System.Security.SecurityCritical] // auto-generated
internal static Guid GetTypeInfoGuid(ITypeInfo typeInfo)
{
Guid result = new Guid ();
FCallGetTypeInfoGuid (ref result, typeInfo);
return result;
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallGetTypeInfoGuid(ref Guid result, ITypeInfo typeInfo);
//====================================================================
// Given a assembly, return the TLBID that will be generated for the
// typelib exported from the assembly.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Guid GetTypeLibGuidForAssembly(Assembly asm)
{
if (asm == null)
throw new ArgumentNullException("asm");
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
if (rtAssembly == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "asm");
Guid result = new Guid();
FCallGetTypeLibGuidForAssembly(ref result, rtAssembly);
return result;
}
[ResourceExposure(ResourceScope.None)] // Scoped to assembly
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallGetTypeLibGuidForAssembly(ref Guid result, RuntimeAssembly asm);
//====================================================================
// Given a assembly, return the version number of the type library
// that would be exported from the assembly.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetTypeLibVersionForAssembly(RuntimeAssembly inputAssembly, out int majorVersion, out int minorVersion);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
public static void GetTypeLibVersionForAssembly(Assembly inputAssembly, out int majorVersion, out int minorVersion)
{
if (inputAssembly == null)
throw new ArgumentNullException("inputAssembly");
Contract.EndContractBlock();
RuntimeAssembly rtAssembly = inputAssembly as RuntimeAssembly;
if (rtAssembly == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "inputAssembly");
_GetTypeLibVersionForAssembly(rtAssembly, out majorVersion, out minorVersion);
}
//====================================================================
// Given a managed object that wraps an UCOMITypeInfo, return its name
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Use System.Runtime.InteropServices.Marshal.GetTypeInfoName(ITypeInfo pTLB) instead. http://go.microsoft.com/fwlink/?linkid=14202&ID=0000011.", false)]
public static String GetTypeInfoName(UCOMITypeInfo pTI)
{
return GetTypeInfoName((ITypeInfo)pTI);
}
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static String GetTypeInfoName(ITypeInfo typeInfo)
{
if (typeInfo == null)
throw new ArgumentNullException("typeInfo");
Contract.EndContractBlock();
String strTypeLibName = null;
String strDocString = null;
int dwHelpContext = 0;
String strHelpFile = null;
typeInfo.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
return strTypeLibName;
}
//====================================================================
// Internal version of GetTypeInfoName
// Support GUID_ManagedName which aligns with TlbImp
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
internal static String GetTypeInfoNameInternal(ITypeInfo typeInfo, out bool hasManagedName)
{
if (typeInfo == null)
throw new ArgumentNullException("typeInfo");
Contract.EndContractBlock();
// Try ManagedNameGuid first
ITypeInfo2 typeInfo2 = typeInfo as ITypeInfo2;
if (typeInfo2 != null)
{
Guid guid = ManagedNameGuid;
object val;
try
{
typeInfo2.GetCustData(ref guid, out val);
}
catch(Exception)
{
val = null;
}
if (val != null && val.GetType() == typeof(string))
{
hasManagedName = true;
return (string)val;
}
}
hasManagedName = false;
return GetTypeInfoName(typeInfo);
}
//====================================================================
// Get the corresponding managed name as converted by TlbImp
// Used to get the type using GetType() from imported assemblies
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
internal static String GetManagedTypeInfoNameInternal(ITypeLib typeLib, ITypeInfo typeInfo)
{
bool hasManagedName;
string name = GetTypeInfoNameInternal(typeInfo, out hasManagedName);
if (hasManagedName)
return name;
else
return GetTypeLibNameInternal(typeLib) + "." + name;
}
//====================================================================
// If a type with the specified GUID is loaded, this method will
// return the reflection type that represents it. Otherwise it returns
// NULL.
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Type GetLoadedTypeForGUID(ref Guid guid);
#if !FEATURE_CORECLR // current implementation requires reflection only load
//====================================================================
// map ITypeInfo* to Type
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Type GetTypeForITypeInfo(IntPtr /* ITypeInfo* */ piTypeInfo)
{
ITypeInfo pTI = null;
ITypeLib pTLB = null;
Type TypeObj = null;
Assembly AsmBldr = null;
TypeLibConverter TlbConverter = null;
int Index = 0;
Guid clsid;
// If the input ITypeInfo is NULL then return NULL.
if (piTypeInfo == IntPtr.Zero)
return null;
// Wrap the ITypeInfo in a CLR object.
pTI = (ITypeInfo)GetObjectForIUnknown(piTypeInfo);
// Check to see if a class exists with the specified GUID.
clsid = GetTypeInfoGuid(pTI);
TypeObj = GetLoadedTypeForGUID(ref clsid);
// If we managed to find the type based on the GUID then return it.
if (TypeObj != null)
return TypeObj;
// There is no type with the specified GUID in the app domain so lets
// try and convert the containing typelib.
try
{
pTI.GetContainingTypeLib(out pTLB, out Index);
}
catch(COMException)
{
pTLB = null;
}
// Check to see if we managed to get a containing typelib.
if (pTLB != null)
{
// Get the assembly name from the typelib.
AssemblyName AsmName = TypeLibConverter.GetAssemblyNameFromTypelib(pTLB, null, null, null, null, AssemblyNameFlags.None);
String AsmNameString = AsmName.FullName;
// Check to see if the assembly that will contain the type already exists.
Assembly[] aAssemblies = Thread.GetDomain().GetAssemblies();
int NumAssemblies = aAssemblies.Length;
for (int i = 0; i < NumAssemblies; i++)
{
if (String.Compare(aAssemblies[i].FullName,
AsmNameString,StringComparison.Ordinal) == 0)
AsmBldr = aAssemblies[i];
}
// If we haven't imported the assembly yet then import it.
if (AsmBldr == null)
{
TlbConverter = new TypeLibConverter();
AsmBldr = TlbConverter.ConvertTypeLibToAssembly(pTLB,
GetTypeLibName(pTLB) + ".dll", 0, new ImporterCallback(), null, null, null, null);
}
// Load the type object from the imported typelib.
// Call GetManagedTypeInfoNameInternal to align with TlbImp behavior
TypeObj = AsmBldr.GetType(GetManagedTypeInfoNameInternal(pTLB, pTI), true, false);
if (TypeObj != null && !TypeObj.IsVisible)
TypeObj = null;
}
else
{
// If the ITypeInfo does not have a containing typelib then simply
// return Object as the type.
TypeObj = typeof(Object);
}
return TypeObj;
}
#endif // #if !FEATURE_CORECLR
// This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it
// on Marshal for more consistent API surface.
#if !FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif //!FEATURE_CORECLR
public static Type GetTypeFromCLSID(Guid clsid)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
}
//====================================================================
// map Type to ITypeInfo*
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr /* ITypeInfo* */ GetITypeInfoForType(Type t);
//====================================================================
// return the IUnknown* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIUnknownForObject(Object o)
{
return GetIUnknownForObjectNative(o, false);
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIUnknownForObjectInContext(Object o)
{
return GetIUnknownForObjectNative(o, true);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetIUnknownForObjectNative(Object o, bool onlyInContext);
//====================================================================
// return the raw IUnknown* for a COM Object not related to current
// context
// Does not call AddRef
//====================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr /* IUnknown* */ GetRawIUnknownForComObjectNoAddRef(Object o);
//====================================================================
// return the IDispatch* for an Object
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IDispatch */ GetIDispatchForObject(Object o)
{
return GetIDispatchForObjectNative(o, false);
}
//====================================================================
// return the IDispatch* for an Object if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetIDispatchForObjectInContext(Object o)
{
return GetIDispatchForObjectNative(o, true);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetIDispatchForObjectNative(Object o, bool onlyInContext);
//====================================================================
// return the IUnknown* representing the interface for the Object
// Object o should support Type T
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T)
{
return GetComInterfaceForObjectNative(o, T, false, true);
}
[System.Security.SecurityCritical]
public static IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
return GetComInterfaceForObject(o, typeof(TInterface));
}
//====================================================================
// return the IUnknown* representing the interface for the Object
// Object o should support Type T, it refer the value of mode to
// invoke customized QueryInterface or not
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(Object o, Type T, CustomQueryInterfaceMode mode)
{
bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
return GetComInterfaceForObjectNative(o, T, false, bEnableCustomizedQueryInterface);
}
//====================================================================
// return the IUnknown* representing the interface for the Object
// Object o should support Type T if the current context
// is the one where the RCW was first seen. Will return null
// otherwise.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr /* IUnknown* */ GetComInterfaceForObjectInContext(Object o, Type t)
{
return GetComInterfaceForObjectNative(o, t, true, true);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr /* IUnknown* */ GetComInterfaceForObjectNative(Object o, Type t, bool onlyInContext, bool fEnalbeCustomizedQueryInterface);
//====================================================================
// return an Object for IUnknown
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetObjectForIUnknown(IntPtr /* IUnknown* */ pUnk);
//====================================================================
// Return a unique Object given an IUnknown. This ensures that you
// receive a fresh object (we will not look in the cache to match up this
// IUnknown to an already existing object). This is useful in cases
// where you want to be able to call ReleaseComObject on a RCW
// and not worry about other active uses of said RCW.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetUniqueObjectForIUnknown(IntPtr unknown);
//====================================================================
// return an Object for IUnknown, using the Type T,
// NOTE:
// Type T should be either a COM imported Type or a sub-type of COM
// imported Type
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetTypedObjectForIUnknown(IntPtr /* IUnknown* */ pUnk, Type t);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern IntPtr CreateAggregatedObject(IntPtr pOuter, Object o);
[System.Security.SecurityCritical]
public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o)
{
return CreateAggregatedObject(pOuter, (object)o);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void CleanupUnusedObjectsInCurrentContext();
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool AreComObjectsAvailableForCleanup();
//====================================================================
// check if the object is classic COM component
//====================================================================
#if !FEATURE_CORECLR // with FEATURE_CORECLR, the whole type is SecurityCritical
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsComObject(Object o);
#endif // FEATURE_COMINTEROP
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr AllocCoTaskMem(int cb)
{
IntPtr pNewMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)cb));
if (pNewMem == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
return pNewMem;
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToCoTaskMemUni(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * 2;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException("s");
IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
fixed (char* firstChar = s)
{
String.wstrcpy((char *)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToCoTaskMemAuto(String s)
{
// Ansi platforms are no longer supported
return StringToCoTaskMemUni(s);
}
[System.Security.SecurityCritical] // auto-generated_required
unsafe public static IntPtr StringToCoTaskMemAnsi(String s)
{
if (s == null)
{
return IntPtr.Zero;
}
else
{
int nb = (s.Length + 1) * SystemMaxDBCSCharSize;
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException("s");
IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
s.ConvertToAnsi((byte *)hglobal, nb, false, false);
return hglobal;
}
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static void FreeCoTaskMem(IntPtr ptr)
{
if (IsNotWin32Atom(ptr)) {
Win32Native.CoTaskMemFree(ptr);
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb)
{
IntPtr pNewMem = Win32Native.CoTaskMemRealloc(pv, new UIntPtr((uint)cb));
if (pNewMem == IntPtr.Zero && cb != 0)
{
throw new OutOfMemoryException();
}
return pNewMem;
}
#if FEATURE_COMINTEROP
//====================================================================
// release the COM component and if the reference hits 0 zombie this object
// further usage of this Object might throw an exception
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static int ReleaseComObject(Object o)
{
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
}
return co.ReleaseSelf();
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int InternalReleaseComObject(Object o);
//====================================================================
// release the COM component and zombie this object
// further usage of this Object might throw an exception
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Int32 FinalReleaseComObject(Object o)
{
if (o == null)
throw new ArgumentNullException("o");
Contract.EndContractBlock();
__ComObject co = null;
// Make sure the obj is an __ComObject.
try
{
co = (__ComObject)o;
}
catch (InvalidCastException)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
}
co.FinalReleaseSelf();
return 0;
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFinalReleaseComObject(Object o);
//====================================================================
// This method retrieves data from the COM object.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Object GetComObjectData(Object obj, Object key)
{
// Validate that the arguments aren't null.
if (obj == null)
throw new ArgumentNullException("obj");
if (key == null)
throw new ArgumentNullException("key");
Contract.EndContractBlock();
__ComObject comObj = null;
// Make sure the obj is an __ComObject.
try
{
comObj = (__ComObject)obj;
}
catch (InvalidCastException)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj");
}
if (obj.GetType().IsWindowsRuntimeObject)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
}
// Retrieve the data from the __ComObject.
return comObj.GetData(key);
}
//====================================================================
// This method sets data on the COM object. The data can only be set
// once for a given key and cannot be removed. This function returns
// true if the data has been added, false if the data could not be
// added because there already was data for the specified key.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static bool SetComObjectData(Object obj, Object key, Object data)
{
// Validate that the arguments aren't null. The data can validly be null.
if (obj == null)
throw new ArgumentNullException("obj");
if (key == null)
throw new ArgumentNullException("key");
Contract.EndContractBlock();
__ComObject comObj = null;
// Make sure the obj is an __ComObject.
try
{
comObj = (__ComObject)obj;
}
catch (InvalidCastException)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "obj");
}
if (obj.GetType().IsWindowsRuntimeObject)
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "obj");
}
// Retrieve the data from the __ComObject.
return comObj.SetData(key, data);
}
//====================================================================
// This method takes the given COM object and wraps it in an object
// of the specified type. The type must be derived from __ComObject.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Object CreateWrapperOfType(Object o, Type t)
{
// Validate the arguments.
if (t == null)
throw new ArgumentNullException("t");
if (!t.IsCOMObject)
throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), "t");
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
Contract.EndContractBlock();
if (t.IsWindowsRuntimeObject)
throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), "t");
// Check for the null case.
if (o == null)
return null;
// Make sure the object is a COM object.
if (!o.GetType().IsCOMObject)
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), "o");
if (o.GetType().IsWindowsRuntimeObject)
throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), "o");
// Check to see if the type of the object is the requested type.
if (o.GetType() == t)
return o;
// Check to see if we already have a cached wrapper for this type.
Object Wrapper = GetComObjectData(o, t);
if (Wrapper == null)
{
// Create the wrapper for the specified type.
Wrapper = InternalCreateWrapperOfType(o, t);
// Attempt to cache the wrapper on the object.
if (!SetComObjectData(o, t, Wrapper))
{
// Another thead already cached the wrapper so use that one instead.
Wrapper = GetComObjectData(o, t);
}
}
return Wrapper;
}
[System.Security.SecurityCritical]
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper));
}
//====================================================================
// Helper method called from CreateWrapperOfType.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object InternalCreateWrapperOfType(Object o, Type t);
//====================================================================
// There may be a thread-based cache of COM components. This service can
// force the aggressive release of the current thread's cache.
//====================================================================
//
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("This API did not perform any operation and will be removed in future versions of the CLR.", false)]
public static void ReleaseThreadCache()
{
}
//====================================================================
// check if the type is visible from COM.
//====================================================================
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsTypeVisibleFromCom(Type t);
//====================================================================
// IUnknown Helpers
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
//====================================================================
// BSTR allocation and dealocation.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static void FreeBSTR(IntPtr ptr)
{
if (IsNotWin32Atom(ptr)) {
Win32Native.SysFreeString(ptr);
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr StringToBSTR(String s)
{
if (s == null)
return IntPtr.Zero;
// Overflow checking
if (s.Length+1 < s.Length)
throw new ArgumentOutOfRangeException("s");
IntPtr bstr = Win32Native.SysAllocStringLen(s, s.Length);
if (bstr == IntPtr.Zero)
throw new OutOfMemoryException();
return bstr;
}
[System.Security.SecurityCritical] // auto-generated_required
public static String PtrToStringBSTR(IntPtr ptr)
{
return PtrToStringUni(ptr, (int)Win32Native.SysStringLen(ptr));
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
[System.Security.SecurityCritical]
public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant)
{
GetNativeVariantForObject((object)obj, pDstNativeVariant);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant );
[System.Security.SecurityCritical]
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
return (T)GetObjectForNativeVariant(pSrcNativeVariant);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars );
[System.Security.SecurityCritical]
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
T[] result = null;
if (objects != null)
{
result = new T[objects.Length];
Array.Copy(objects, result, objects.Length);
}
return result;
}
/// <summary>
/// <para>Returns the first valid COM slot that GetMethodInfoForSlot will work on
/// This will be 3 for IUnknown based interfaces and 7 for IDispatch based interfaces. </para>
/// </summary>
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetStartComSlot(Type t);
/// <summary>
/// <para>Returns the last valid COM slot that GetMethodInfoForSlot will work on. </para>
/// </summary>
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetEndComSlot(Type t);
/// <summary>
/// <para>Returns the MemberInfo that COM callers calling through the exposed
/// vtable on the given slot will be calling. The slot should take into account
/// if the exposed interface is IUnknown based or IDispatch based.
/// For classes, the lookup is done on the default interface that will be
/// exposed for the class. </para>
/// </summary>
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern MemberInfo GetMethodInfoForComSlot(Type t, int slot, ref ComMemberType memberType);
/// <summary>
/// <para>Returns the COM slot for a memeber info, taking into account whether
/// the exposed interface is IUnknown based or IDispatch based</para>
/// </summary>
[System.Security.SecurityCritical] // auto-generated_required
public static int GetComSlotForMethodInfo(MemberInfo m)
{
if (m== null)
throw new ArgumentNullException("m");
if (!(m is RuntimeMethodInfo))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "m");
if (!m.DeclaringType.IsInterface)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeInterfaceMethod"), "m");
if (m.DeclaringType.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "m");
Contract.EndContractBlock();
return InternalGetComSlotForMethodInfo((IRuntimeMethodInfo)m);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalGetComSlotForMethodInfo(IRuntimeMethodInfo m);
//====================================================================
// This method generates a GUID for the specified type. If the type
// has a GUID in the metadata then it is returned otherwise a stable
// guid GUID is generated based on the fully qualified name of the
// type.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Guid GenerateGuidForType(Type type)
{
Guid result = new Guid ();
FCallGenerateGuidForType (ref result, type);
return result;
}
// The full assembly name is used to compute the GUID, so this should be SxS-safe
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallGenerateGuidForType(ref Guid result, Type type);
//====================================================================
// This method generates a PROGID for the specified type. If the type
// has a PROGID in the metadata then it is returned otherwise a stable
// PROGID is generated based on the fully qualified name of the
// type.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static String GenerateProgIdForType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
if (type.IsImport)
throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), "type");
if (type.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "type");
Contract.EndContractBlock();
if (!RegistrationServices.TypeRequiresRegistrationHelper(type))
throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"), "type");
IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
for (int i = 0; i < cas.Count; i ++)
{
if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute))
{
// Retrieve the PROGID string from the ProgIdAttribute.
IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
Contract.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
Contract.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
String strProgId = (String)progIdConstructorArg.Value;
if (strProgId == null)
strProgId = String.Empty;
return strProgId;
}
}
// If there is no prog ID attribute then use the full name of the type as the prog id.
return type.FullName;
}
//====================================================================
// This method binds to the specified moniker.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static Object BindToMoniker(String monikerName)
{
Object obj = null;
IBindCtx bindctx = null;
CreateBindCtx(0, out bindctx);
UInt32 cbEaten;
IMoniker pmoniker = null;
MkParseDisplayName(bindctx, monikerName, out cbEaten, out pmoniker);
BindMoniker(pmoniker, 0, ref IID_IUnknown, out obj);
return obj;
}
//====================================================================
// This method gets the currently running object.
//====================================================================
[System.Security.SecurityCritical] // auto-generated_required
public static Object GetActiveObject(String progID)
{
Object obj = null;
Guid clsid;
// Call CLSIDFromProgIDEx first then fall back on CLSIDFromProgID if
// CLSIDFromProgIDEx doesn't exist.
try
{
CLSIDFromProgIDEx(progID, out clsid);
}
// catch
catch(Exception)
{
CLSIDFromProgID(progID, out clsid);
}
GetActiveObject(ref clsid, IntPtr.Zero, out obj);
return obj;
}
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgIDEx([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] String progId, out Guid clsid);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.Machine)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
[DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
[DllImport(Microsoft.Win32.Win32Native.OLEAUT32, PreserveSig = false)]
[ResourceExposure(ResourceScope.None)]
[SuppressUnmanagedCodeSecurity]
[System.Security.SecurityCritical] // auto-generated
private static extern void GetActiveObject(ref Guid rclsid, IntPtr reserved, [MarshalAs(UnmanagedType.Interface)] out Object ppunk);
//========================================================================
// Private method called from remoting to support ServicedComponents.
//========================================================================
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool InternalSwitchCCW(Object oldtp, Object newtp);
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object InternalWrapIUnknownWithComObject(IntPtr i);
//========================================================================
// Private method called from EE upon use of license/ICF2 marshaling.
//========================================================================
[SecurityCritical]
private static IntPtr LoadLicenseManager()
{
Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version +
", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
Type t = sys.GetType("System.ComponentModel.LicenseManager");
if (t == null || !t.IsVisible)
return IntPtr.Zero;
return t.TypeHandle.Value;
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void ChangeWrapperHandleStrength(Object otp, bool fIsWeak);
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InitializeWrapperForWinRT(object o, ref IntPtr pUnk);
#if FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InitializeManagedWinRTFactoryObject(object o, RuntimeType runtimeClassType);
#endif
//========================================================================
// Create activation factory and wraps it with a unique RCW
//========================================================================
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object GetNativeActivationFactory(Type type);
//========================================================================
// Methods allowing retrieval of the IIDs exposed by an underlying WinRT
// object, as specified by the object's IInspectable::GetIids()
//========================================================================
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetInspectableIids(ObjectHandleOnStack obj, ObjectHandleOnStack guids);
[System.Security.SecurityCritical]
internal static System.Guid[] GetInspectableIids(object obj)
{
System.Guid[] result = null;
System.__ComObject comObj = obj as System.__ComObject;
if (comObj != null)
{
_GetInspectableIids(JitHelpers.GetObjectHandleOnStack(ref comObj),
JitHelpers.GetObjectHandleOnStack(ref result));
}
return result;
}
//========================================================================
// Methods allowing retrieval of the cached WinRT type corresponding to
// the specified GUID
//========================================================================
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetCachedWinRTTypeByIid(
ObjectHandleOnStack appDomainObj,
System.Guid iid,
out IntPtr rthHandle);
[System.Security.SecurityCritical]
internal static System.Type GetCachedWinRTTypeByIid(
System.AppDomain ad,
System.Guid iid)
{
IntPtr rthHandle;
_GetCachedWinRTTypeByIid(JitHelpers.GetObjectHandleOnStack(ref ad),
iid,
out rthHandle);
System.Type res = Type.GetTypeFromHandleUnsafe(rthHandle);
return res;
}
//========================================================================
// Methods allowing retrieval of the WinRT types cached in the specified
// app domain
//========================================================================
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _GetCachedWinRTTypes(
ObjectHandleOnStack appDomainObj,
ref int epoch,
ObjectHandleOnStack winrtTypes);
[System.Security.SecurityCritical]
internal static System.Type[] GetCachedWinRTTypes(
System.AppDomain ad,
ref int epoch)
{
System.IntPtr[] res = null;
_GetCachedWinRTTypes(JitHelpers.GetObjectHandleOnStack(ref ad),
ref epoch,
JitHelpers.GetObjectHandleOnStack(ref res));
System.Type[] result = new System.Type[res.Length];
for (int i = 0; i < res.Length; ++i)
{
result[i] = Type.GetTypeFromHandleUnsafe(res[i]);
}
return result;
}
[System.Security.SecurityCritical]
internal static System.Type[] GetCachedWinRTTypes(
System.AppDomain ad)
{
int dummyEpoch = 0;
return GetCachedWinRTTypes(ad, ref dummyEpoch);
}
#endif // FEATURE_COMINTEROP
[System.Security.SecurityCritical] // auto-generated_required
public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t)
{
// Validate the parameters
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("ptr");
if (t == null)
throw new ArgumentNullException("t");
Contract.EndContractBlock();
if ((t as RuntimeType) == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
Type c = t.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "t");
return GetDelegateForFunctionPointerInternal(ptr, t);
}
[System.Security.SecurityCritical]
public static TDelegate GetDelegateForFunctionPointer<TDelegate>(IntPtr ptr)
{
return (TDelegate)(object)GetDelegateForFunctionPointer(ptr, typeof(TDelegate));
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t);
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
if (d == null)
throw new ArgumentNullException("d");
Contract.EndContractBlock();
return GetFunctionPointerForDelegateInternal(d);
}
[System.Security.SecurityCritical]
public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d)
{
return GetFunctionPointerForDelegate((Delegate)(object)d);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
#if FEATURE_COMINTEROP
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToBSTR(SecureString s) {
if( s == null) {
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
return s.ToBSTR();
}
#endif
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
if( s == null) {
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
return s.ToAnsiStr(false);
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
return s.ToUniStr(false);
}
#if FEATURE_COMINTEROP
[System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeBSTR(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.SysStringLen(s) * 2));
FreeBSTR(s);
}
#endif
[System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeCoTaskMemAnsi(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeCoTaskMem(s);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeCoTaskMemUnicode(IntPtr s)
{
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeCoTaskMem(s);
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
if( s == null) {
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
return s.ToAnsiStr(true);
}
[System.Security.SecurityCritical] // auto-generated_required
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) {
if( s == null) {
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
return s.ToUniStr(true);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeGlobalAllocAnsi(IntPtr s) {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeHGlobal(s);
}
[System.Security.SecurityCritical] // auto-generated_required
public static void ZeroFreeGlobalAllocUnicode(IntPtr s) {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeHGlobal(s);
}
}
#if FEATURE_COMINTEROP && !FEATURE_CORECLR // current implementation requires reflection only load
//========================================================================
// Typelib importer callback implementation.
//========================================================================
internal class ImporterCallback : ITypeLibImporterNotifySink
{
public void ReportEvent(ImporterEventKind EventKind, int EventCode, String EventMsg)
{
}
[System.Security.SecuritySafeCritical] // overrides transparent public member
public Assembly ResolveRef(Object TypeLib)
{
try
{
// Create the TypeLibConverter.
ITypeLibConverter TLBConv = new TypeLibConverter();
// Convert the typelib.
return TLBConv.ConvertTypeLibToAssembly(TypeLib,
Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll",
0,
new ImporterCallback(),
null,
null,
null,
null);
}
catch(Exception)
// catch
{
return null;
}
}
}
#endif // FEATURE_COMINTEROP && !FEATURE_CORECLR
}
|