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
use crate::{bindings::*, invoker::GlobalFunction, value::FromValueOwned, *};
use std::{borrow::Cow, ops::Deref};

/// Session对象
#[repr(transparent)]
pub struct Session {
    ptr: pbsession
}

impl Session {
    pub(crate) unsafe fn from_ptr(ptr: pbsession) -> Session {
        Session {
            ptr
        }
    }
    pub(crate) fn as_ptr(&self) -> pbsession { self.ptr }

    /// 克隆Session对象
    ///
    /// # Safety
    ///
    /// 此方法不能延长Session对象的生命周期,因此不能保证克隆后的Session对象始终有效,生命周期将始终与此对象一样
    pub unsafe fn clone(&self) -> Session {
        Session {
            ptr: self.ptr
        }
    }

    /// 判断是否有重启Session的请求 (在PowerScript中调用了`Restart`函数)
    pub fn restart_requested(&self) -> bool { unsafe { ffi::pbsession_RestartRequested(self.ptr).into() } }

    /// 是否创建了可视化对象 (打开了顶层窗口)
    pub fn has_visual_object(&self) -> bool { unsafe { ffi::pbsession_HasPBVisualObject(self.ptr).into() } }

    /// 处理PB消息
    ///
    /// # Notice
    ///
    /// 开启了消息循环后,需要处理PB的消息以执行PowerScript中的`Post`调用
    pub fn process_message(&self) -> bool { unsafe { ffi::pbsession_ProcessPBMessage(self.ptr).into() } }

    /// 获取系统类组
    pub(crate) fn get_system_group(&self) -> pbgroup { unsafe { ffi::pbsession_GetSystemGroup(self.ptr) } }

    /// 查找指定名称的类组
    pub(crate) fn find_group(&self, name: impl AsPBStr, r#type: GroupType) -> Option<pbgroup> {
        unsafe { ffi::pbsession_FindGroup(self.ptr, name.as_pbstr().as_ptr(), r#type) }
    }

    /// 在指定组下查找类定义
    pub(crate) fn find_class(&self, group: pbgroup, name: impl AsPBStr) -> Option<pbclass> {
        unsafe { ffi::pbsession_FindClass(self.ptr, group, name.as_pbstr().as_ptr()) }
    }

    /// 获取类定义的组
    ///
    /// FIXME: 此方法通过类名反查类所在的组,目前PBNI没有提供直接的获取方法
    pub(crate) fn get_group(&self, mut cls: pbclass) -> Option<pbgroup> {
        unsafe {
            'outer: loop {
                let cls_name = ffi::pbsession_GetClassName(self.ptr, cls);
                for group_type in (GroupType::Application as i32)..(GroupType::Unknown as i32) {
                    let group = ffi::pbsession_FindGroup(self.ptr, cls_name, group_type.into());
                    if group.is_some() {
                        break 'outer group;
                    }
                }
                match ffi::pbsession_GetSuperClass(self.ptr, cls) {
                    Some(v) => cls = v,
                    None => break None
                }
            }
        }
    }

    /*
        Exception
    */

    /// 检查当前是否有异常未处理
    pub fn has_exception(&self) -> bool { unsafe { ffi::pbsession_HasExceptionThrown(self.ptr).into() } }

    /// 清除异常
    pub fn clear_exception(&self) {
        unsafe {
            ffi::pbsession_ClearException(self.ptr);
        }
    }

    /// 抛出`PBXRuntimeError`异常
    ///
    /// # Exmaples
    ///
    /// ```
    /// session.throw_exception("test");
    /// // 使用宏
    /// throw!(session,"this is a {}!","exception");
    /// ```
    pub fn throw_exception(&self, exstr: impl AsPBStr) -> Result<()> {
        let mut ex = self.new_system_object(pbstr!("PBXRuntimeError"))?;
        unsafe { ex.set_var_str_unchecked(pbstr!("text"), exstr)? };
        unsafe {
            ffi::pbsession_ThrowException(self.ptr, ex.as_ptr());
        }
        Ok(())
    }

    /*
        Prop
    */

    /// 与Session绑定`static`引用参数
    pub fn set_prop<T, D>(&self, name: T, data: &'static D)
    where
        T: AsPBStr,
        D: Sized
    {
        self.set_prop_ptr(name, data as *const D)
    }

    /// 与Session绑定指针参数
    pub fn set_prop_ptr<T, D>(&self, name: T, data: *const D)
    where
        T: AsPBStr,
        D: Sized
    {
        unsafe { ffi::pbsession_SetProp(self.ptr, name.as_pbstr().as_ptr(), data as _) }
    }

    /// 获取Session绑定的指针参数
    pub fn get_prop_ptr<T, D>(&self, name: T) -> *const D
    where
        T: AsPBStr,
        D: Sized
    {
        unsafe { ffi::pbsession_GetProp(self.ptr, name.as_pbstr().as_ptr()) as *const D }
    }
    /// 获取Session绑定的引用参数
    ///
    ///
    /// # Safety
    ///
    /// 引用的生命周期由调用处提供,需要开发者自行保证期有效性
    pub unsafe fn get_prop_ref<'a, T, D>(&self, name: T) -> Option<&'a D>
    where
        T: AsPBStr,
        D: Sized
    {
        let ptr: *const D = self.get_prop_ptr(name);
        if ptr.is_null() {
            None
        } else {
            Some(&*ptr)
        }
    }

    /// 获取Session绑定的可变引用参数
    ///
    ///
    /// # Safety
    ///
    /// 引用的生命周期由调用处提供,需要开发者自行保证期有效性
    pub unsafe fn get_prop_mut<'a, T, D>(&self, name: T) -> Option<&'a mut D>
    where
        T: AsPBStr,
        D: Sized
    {
        let ptr: *const D = self.get_prop_ptr(name);
        if ptr.is_null() {
            None
        } else {
            Some(&mut *(ptr as *mut D))
        }
    }

    /// 解绑Session参数
    ///
    /// # Notice
    ///
    /// 如果绑定的参数内存是由`Box`分配的,那么需要在解绑前正确释放内存
    pub fn remove_prop(&self, name: impl AsPBStr) {
        unsafe { ffi::pbsession_RemoveProp(self.ptr, name.as_pbstr().as_ptr()) }
    }

    /*
        Enum
    */

    /// 获取指定名称枚举的值,不区分大小写
    ///
    /// # Examples
    ///
    /// ```
    /// // `Center!`枚举的值
    /// session.get_enum_item_value("Aligment","Center");
    /// ```
    pub fn get_enum_item_value(&self, enum_name: impl AsPBStr, item_name: impl AsPBStr) -> pblong {
        unsafe {
            ffi::pbsession_GetEnumItemValue(
                self.ptr,
                enum_name.as_pbstr().as_ptr(),
                item_name.as_pbstr().as_ptr()
            )
        }
    }

    /// 获取枚举值的枚举名称,不区分大小写
    ///
    /// # Examples
    ///
    /// ```
    /// let val = session.get_enum_item_value("Aligment","Center");
    /// let name = session.get_enum_item_name("Aligment",val); //center
    /// ```
    pub fn get_enum_item_name<'a>(
        &'a self,
        enum_name: impl AsPBStr,
        item_value: pblong
    ) -> Option<&'a PBStr> {
        unsafe {
            let cstr = ffi::pbsession_GetEnumItemName(self.ptr, enum_name.as_pbstr().as_ptr(), item_value);
            if cstr.is_null() {
                None
            } else {
                Some(PBStr::from_ptr_str(cstr))
            }
        }
    }

    /*
        String
    */

    #[inline]
    pub(crate) unsafe fn get_string_unchecked<'a>(&self, pbstr: pbstring) -> &'a PBStr {
        let cstr = ffi::pbsession_GetString(self.ptr, pbstr);
        PBStr::from_ptr_str(cstr)
    }

    /*
        Object
    */

    /// 实例化用户自定义对象
    ///
    /// # Examples
    ///
    /// ```
    /// let obj = session.new_user_object("n_cst_object");
    /// ```
    pub fn new_user_object<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Object<'a>> {
        unsafe {
            let cls_name = cls_name.as_pbstr();
            let group = self
                .find_group(cls_name.as_ref(), GroupType::UserObject)
                .ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
            let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
            let ptr = ffi::pbsession_NewObject(self.ptr, cls);
            Ok(Object::from_ptr(ptr, self.clone()))
        }
    }

    /// 实例化系统对象
    ///
    /// # Examples
    ///
    /// ```
    /// let obj = session.new_system_object("datastore");
    /// ```
    pub fn new_system_object<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Object<'a>> {
        unsafe {
            let group = self.get_system_group();
            let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
            let ptr = ffi::pbsession_NewObject(self.ptr, cls);
            Ok(Object::from_ptr(ptr, self.clone()))
        }
    }

    /// 实例化任意PB对象 (包括用户自定义对象和系统对象)
    ///
    /// # Examples
    ///
    /// ```
    /// let obj = session.new_object("n_cst_object");
    /// let obj = session.new_object("datastore");
    /// ```
    pub fn new_object<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Object<'a>> {
        let cls_name = cls_name.as_pbstr();
        self.new_user_object(cls_name.as_ref()).or_else(|_| self.new_system_object(cls_name))
    }

    /*
        Array
    */

    /// 实例化变长标量一维数组
    ///
    /// # Parameters
    ///
    /// - **item_type** 元素标量类型
    ///
    /// # Examples
    ///
    /// ```
    /// //int arr[]
    /// let mut arr = session.new_array(ValueType::Int).unwrap();
    /// //arr[1] = 123
    /// arr.set_item_int(&[1],123);
    /// ```
    pub fn new_array<'a>(&'a self, item_type: ValueType) -> Result<Array<'a>> {
        unsafe {
            let ptr = ffi::pbsession_NewUnboundedSimpleArray(self.ptr, item_type)
                .ok_or(PBXRESULT::E_INVALID_ARGUMENT)?;
            Ok(Array::from_ptr(ptr, false, self.clone()))
        }
    }

    /// 实例化定长标量多维数组
    ///
    /// # Parameters
    ///
    /// - **item_type** 元素标量类型
    /// - **dims** `&[(下标,上标)]`
    ///
    /// # Examples
    ///
    /// ```
    /// //int arr[10]
    /// let mut arr = session.new_bounded_array(ValueType::Int,&[(1,10)]).unwrap();
    /// //arr[1] = 123
    /// arr.set_item_int(&[1],123);
    ///
    /// //int arr[2,4]
    /// let mut arr = session.new_bounded_array(ValueType::Int,&[(1,2),(1,4)]).unwrap();
    /// //arr[1,2] = 123
    /// arr.set_item_int(&[1,2],123);
    ///
    /// //int arr[1 to 5,2 to 10]
    /// let mut arr = session.new_bounded_array(ValueType::Int,&[(1,5),(2,10)]).unwrap();
    /// //arr[1,2] = 123
    /// arr.set_item_int(&[1,2],123);
    /// ```
    pub fn new_bounded_array<'a>(
        &'a self,
        item_type: ValueType,
        dims: &[(pblong, pblong)]
    ) -> Result<Array<'a>> {
        unsafe {
            let dims: Vec<ArrayBound> = dims
                .iter()
                .map(|&(lowerBound, upperBound)| {
                    ArrayBound {
                        lowerBound,
                        upperBound
                    }
                })
                .collect();
            let ptr =
                ffi::pbsession_NewBoundedSimpleArray(self.ptr, item_type, dims.len() as u16, dims.as_ptr())
                    .ok_or(PBXRESULT::E_INVALID_ARGUMENT)?;
            Ok(Array::from_ptr(ptr, false, self.clone()))
        }
    }

    /// 实例化变长用户自定义对象一维数组
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    ///
    /// # Examples
    ///
    /// ```
    /// //n_cst_test arr[]
    /// let mut arr = session.new_user_object_array("n_cst_test").unwrap();
    /// //arr[1] = Create n_cst_test
    /// let obj = session.new_user_object("n_cst_test").unwrap();
    /// arr.set_item_object(&[1],&obj);
    /// ```
    pub fn new_user_object_array<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Array<'a>> {
        let cls_name = cls_name.as_pbstr();
        let group =
            self.find_group(cls_name.as_ref(), GroupType::UserObject).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        self.new_object_array_impl(cls)
    }

    /// 实例化变长系统对象一维数组
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    ///
    /// # Examples
    ///
    /// ```
    /// //datastore arr[]
    /// let mut arr = session.new_system_object_array("datastore").unwrap();
    /// //arr[1] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1],&obj);
    /// ```
    pub fn new_system_object_array<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Array<'a>> {
        let group = self.get_system_group();
        let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        self.new_object_array_impl(cls)
    }

    /// 实例化变长任意对象一维数组 (包括用户自定义对象和系统对象)
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    ///
    /// # Examples
    ///
    /// ```
    /// //datastore arr[]
    /// let mut arr = session.new_object_array("datastore").unwrap();
    /// //arr[1] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1],&obj);
    /// ```
    pub fn new_object_array<'a>(&'a self, cls_name: impl AsPBStr) -> Result<Array<'a>> {
        let cls_name = cls_name.as_pbstr();
        self.new_user_object_array(cls_name.as_ref()).or_else(|_| self.new_system_object_array(cls_name))
    }

    fn new_object_array_impl<'a>(&'a self, cls: pbclass) -> Result<Array<'a>> {
        unsafe {
            let ptr =
                ffi::pbsession_NewUnboundedObjectArray(self.ptr, cls).ok_or(PBXRESULT::E_INVALID_ARGUMENT)?;
            Ok(Array::from_ptr(ptr, true, self.clone()))
        }
    }

    /// 实例化定长用户自定义对象多维数组
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    /// - **dims** `&[(下标,上标)]`
    ///
    /// # Examples
    ///
    /// ```
    /// //n_cst_test arr[10]
    /// let mut arr = session.new_bounded_user_object_array("n_cst_test",&[(1,10)]).unwrap();
    /// //arr[1] = Create n_cst_test
    /// let obj = session.new_user_object("n_cst_test").unwrap();
    /// arr.set_item_object(&[1],&obj);
    ///
    /// //n_cst_test arr[2,4]
    /// let mut arr = session.new_bounded_user_object_array("n_cst_test",&[(1,2),(1,4)]).unwrap();
    /// //arr[1,2] = Create n_cst_test
    /// let obj = session.new_user_object("n_cst_test").unwrap();
    /// arr.set_item_object(&[1,2],&obj);
    ///
    /// //n_cst_test arr[1 to 5,2 to 10]
    /// let mut arr = session.new_bounded_user_object_array("n_cst_test",&[(1,5),(2,10)]).unwrap();
    /// //arr[1,2] = Create n_cst_test
    /// arr.set_item_object(&[1,2],&obj);
    /// ```
    pub fn new_bounded_user_object_array<'a>(
        &'a self,
        cls_name: impl AsPBStr,
        dims: &[(pblong, pblong)]
    ) -> Result<Array<'a>> {
        let cls_name = cls_name.as_pbstr();
        let group =
            self.find_group(cls_name.as_ref(), GroupType::UserObject).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        self.new_bounded_object_array_impl(cls, dims)
    }

    /// 实例化定长用户自定义对象多维数组
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    /// - **dims** `&[(下标,上标)]`
    ///
    /// # Examples
    ///
    /// ```
    /// //datastore arr[10]
    /// let mut arr = session.new_bounded_system_object_array("datastore",&[(1,10)]).unwrap();
    /// //arr[1] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1],&obj);
    ///
    /// //datastore arr[2,4]
    /// let mut arr = session.new_bounded_system_object_array("datastore",&[(1,2),(1,4)]).unwrap();
    /// //arr[1,2] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1,2],&obj);
    ///
    /// //datastore arr[1 to 5,2 to 10]
    /// let mut arr = session.new_bounded_system_object_array("datastore",&[(1,5),(2,10)]).unwrap();
    /// //arr[1,2] = Create datastore
    /// arr.set_item_object(&[1,2],&obj);
    /// ```
    pub fn new_bounded_system_object_array<'a>(
        &'a self,
        cls_name: impl AsPBStr,
        dims: &[(pblong, pblong)]
    ) -> Result<Array<'a>> {
        let group = self.get_system_group();
        let cls = self.find_class(group, cls_name).ok_or(PBXRESULT::E_NO_SUCH_CLASS)?;
        self.new_bounded_object_array_impl(cls, dims)
    }

    /// 实例化定长任意对象多维数组
    ///
    /// # Parameters
    ///
    /// - **cls_name** 元素对象类名
    /// - **dims** `&[(下标,上标)]`
    ///
    /// # Examples
    ///
    /// ```
    /// //datastore arr[10]
    /// let mut arr = session.new_bounded_object_array("datastore",&[(1,10)]).unwrap();
    /// //arr[1] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1],&obj);
    ///
    /// //datastore arr[2,4]
    /// let mut arr = session.new_bounded_object_array("datastore",&[(1,2),(1,4)]).unwrap();
    /// //arr[1,2] = Create datastore
    /// let obj = session.new_user_object("datastore").unwrap();
    /// arr.set_item_object(&[1,2],&obj);
    ///
    /// //datastore arr[1 to 5,2 to 10]
    /// let mut arr = session.new_bounded_object_array("datastore",&[(1,5),(2,10)]).unwrap();
    /// //arr[1,2] = Create datastore
    /// arr.set_item_object(&[1,2],&obj);
    /// ```
    pub fn new_bounded_object_array<'a>(
        &'a self,
        cls_name: impl AsPBStr,
        dims: &[(pblong, pblong)]
    ) -> Result<Array<'a>> {
        let cls_name = cls_name.as_pbstr();
        self.new_bounded_user_object_array(cls_name.as_ref(), dims)
            .or_else(|_| self.new_bounded_system_object_array(cls_name, dims))
    }

    fn new_bounded_object_array_impl<'a>(
        &'a self,
        cls: pbclass,
        dims: &[(pblong, pblong)]
    ) -> Result<Array<'a>> {
        unsafe {
            let dims: Vec<ArrayBound> = dims
                .iter()
                .map(|&(lowerBound, upperBound)| {
                    ArrayBound {
                        lowerBound,
                        upperBound
                    }
                })
                .collect();
            let ptr = ffi::pbsession_NewBoundedObjectArray(self.ptr, cls, dims.len() as u16, dims.as_ptr())
                .ok_or(PBXRESULT::E_INVALID_ARGUMENT)?;
            Ok(Array::from_ptr(ptr, true, self.clone()))
        }
    }

    /*
        Blob
    */

    pub(crate) fn new_pbblob(&self, bin: impl AsRef<[u8]>) -> pbblob {
        let bin = bin.as_ref();
        assert!(!bin.is_empty());
        unsafe { ffi::pbsession_NewBlob(self.ptr, bin.as_ptr() as _, bin.len() as pblong) }
    }
    pub(crate) unsafe fn get_blob_unchecked<'a>(&self, pbbin: pbblob) -> &'a [u8] {
        let ptr = ffi::pbsession_GetBlob(self.ptr, pbbin);
        let len = if !ptr.is_null() {
            ffi::pbsession_GetBlobLength(self.ptr, pbbin)
        } else {
            0
        };
        std::slice::from_raw_parts(ptr as *const u8, len as usize)
    }

    /*
        Date, Time and DateTime
    */

    #[cfg(feature = "datetime")]
    pub(crate) fn new_pbdate(&self, dt: NaiveDate) -> pbdate {
        unsafe {
            let pbdt = ffi::pbsession_NewDate(self.ptr);
            let pbxr = ffi::pbsession_SetDate(
                self.ptr,
                pbdt,
                dt.year() as pbint,
                dt.month() as pbint,
                dt.day() as pbint
            );
            assert!(pbxr == PBXRESULT::OK);
            pbdt
        }
    }
    #[cfg(feature = "datetime")]
    pub(crate) fn new_pbtime(&self, tm: NaiveTime) -> pbtime {
        unsafe {
            let pbtm = ffi::pbsession_NewTime(self.ptr);
            let pbxr = ffi::pbsession_SetTime(
                self.ptr,
                pbtm,
                tm.hour() as pbint,
                tm.minute() as pbint,
                tm.second() as pbdouble + tm.nanosecond() as pbdouble / 1000_000_000.0
            );
            assert!(pbxr == PBXRESULT::OK);
            pbtm
        }
    }
    #[cfg(feature = "datetime")]
    pub(crate) fn new_pbdatetime(&self, dtt: NaiveDateTime) -> pbdatetime {
        unsafe {
            let pbdtt = ffi::pbsession_NewDateTime(self.ptr);
            let pbxr = ffi::pbsession_SetDateTime(
                self.ptr,
                pbdtt,
                dtt.year() as pbint,
                dtt.month() as pbint,
                dtt.day() as pbint,
                dtt.hour() as pbint,
                dtt.minute() as pbint,
                dtt.second() as pbdouble + dtt.nanosecond() as pbdouble / 1000_000_000.0
            );
            assert!(pbxr == PBXRESULT::OK);
            pbdtt
        }
    }
    #[cfg(feature = "datetime")]
    pub(crate) unsafe fn get_date_unchecked(&self, pbdt: pbdate) -> NaiveDate {
        let mut year = 0;
        let mut month = 0;
        let mut day = 0;
        let pbxr = ffi::pbsession_SplitDate(self.ptr, pbdt, &mut year, &mut month, &mut day);
        assert!(pbxr == PBXRESULT::OK);
        NaiveDate::from_ymd(year as i32, month as u32, day as u32)
    }
    #[cfg(feature = "datetime")]
    pub(crate) unsafe fn get_time_unchecked(&self, pbtm: pbtime) -> NaiveTime {
        let mut hour = 0;
        let mut minute = 0;
        let mut second = 0.0;
        let pbxr = ffi::pbsession_SplitTime(self.ptr, pbtm, &mut hour, &mut minute, &mut second);
        assert!(pbxr == PBXRESULT::OK);
        NaiveTime::from_hms_nano(
            hour as u32,
            minute as u32,
            second as u32,
            ((second - second.trunc()) * 1000_000_000.0) as u32
        )
    }
    #[cfg(feature = "datetime")]
    pub(crate) unsafe fn get_datetime_unchecked(&self, pbdtt: pbdatetime) -> NaiveDateTime {
        let mut year = 0;
        let mut month = 0;
        let mut day = 0;
        let mut hour = 0;
        let mut minute = 0;
        let mut second = 0.0;
        let pbxr = ffi::pbsession_SplitDateTime(
            self.ptr,
            pbdtt,
            &mut year,
            &mut month,
            &mut day,
            &mut hour,
            &mut minute,
            &mut second
        );
        assert!(pbxr == PBXRESULT::OK);
        NaiveDateTime::new(
            NaiveDate::from_ymd(year as i32, month as u32, day as u32),
            NaiveTime::from_hms_nano(
                hour as u32,
                minute as u32,
                second as u32,
                ((second - second.trunc()) * 1000_000_000.0) as u32
            )
        )
    }

    /*
        Decimal number
    */
    #[cfg(feature = "decimal")]
    pub(crate) fn new_pbdec(&self, dec: Decimal) -> pbdec {
        unsafe {
            let dec = PBString::from_str_unchecked(dec.to_string());
            let pbdec = ffi::pbsession_NewDecimal(self.ptr);
            let pbxr = ffi::pbsession_SetDecimal(self.ptr, pbdec, dec.as_ptr());
            assert!(pbxr == PBXRESULT::OK);
            pbdec
        }
    }
    #[cfg(feature = "decimal")]
    pub(crate) unsafe fn get_dec_unchecked(&self, pbdec: pbdec) -> Decimal {
        let cstr = ffi::pbsession_GetDecimalString(self.ptr, pbdec);
        let str = String::from_pbstr_unchecked(cstr);
        ffi::pbsession_ReleaseDecimalString(self.ptr, cstr);
        str.parse().unwrap()
    }
}

/*
    Global variable
*/

/// 全局变量ID抽象
pub trait GlobalVarId {
    fn var_id(&self, session: &Session) -> FieldId;
}

impl<T: AsPBStr> GlobalVarId for T {
    #[inline]
    fn var_id(&self, session: &Session) -> FieldId {
        let pbstr = self.as_pbstr();
        session
            .get_var_id(pbstr.as_ref())
            .ok_or_else(|| format!("invalid global var {}", pbstr.to_string_lossy()))
            .unwrap()
    }
}
impl GlobalVarId for FieldId {
    #[inline]
    fn var_id(&self, _session: &Session) -> FieldId { *self }
}
impl GlobalVarId for Option<FieldId> {
    #[inline]
    fn var_id(&self, _session: &Session) -> FieldId { self.unwrap() }
}

impl Session {
    /// 获取全局变量ID
    ///
    /// # Examples
    ///
    /// ```
    /// let fid = session.get_var_id("gs_var").unwrap();
    /// session.set_var_str(fid,"rust");
    /// ```
    pub fn get_var_id(&self, name: impl AsPBStr) -> Option<FieldId> {
        unsafe {
            let fid = ffi::pbsession_GetGlobalVarID(self.ptr, name.as_pbstr().as_ptr());
            if fid.is_undefined() {
                None
            } else {
                Some(fid)
            }
        }
    }

    /// 判断是否存在指定全局变量
    ///
    /// # Examples
    ///
    /// ```
    /// if session.has_var("gs_var") {
    ///     session.set_var_str("gs_var","rust");
    /// }
    /// ```
    pub fn has_var(&self, name: impl AsPBStr) -> bool { self.get_var_id(name).is_some() }

    /// 获取指定全局变量类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Examples
    ///
    /// ```
    /// if session.get_var_type("gs_var") == ValueType::String {
    ///     session.set_var_str("gs_var","rust");
    /// }
    /// ```
    pub fn get_var_type(&self, fid: impl GlobalVarId) -> ValueType {
        unsafe { ffi::pbsession_GetGlobalVarType(self.ptr, fid.var_id(self)) }
    }

    /// 判断指定全局变量是否为NULL
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    pub fn is_var_null(&self, fid: impl GlobalVarId) -> bool {
        unsafe { ffi::pbsession_IsGlobalVarNull(self.ptr, fid.var_id(self)).into() }
    }

    /// 判断指定全局变量是否为数组类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    pub fn is_var_array(&self, fid: impl GlobalVarId) -> bool {
        unsafe { ffi::pbsession_IsGlobalVarArray(self.ptr, fid.var_id(self)).into() }
    }

    /// 判断指定全局变量是否为对象类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    pub fn is_var_object(&self, fid: impl GlobalVarId) -> bool {
        unsafe { ffi::pbsession_IsGlobalVarObject(self.ptr, fid.var_id(self)).into() }
    }

    /// 获取`int`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_int(&self, fid: impl GlobalVarId) -> Option<pbint> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Int);
        unsafe { self.get_var_int_unchecked(fid) }
    }

    /// 获取`int`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_int_unchecked(&self, fid: impl GlobalVarId) -> Option<pbint> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetIntGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`uint`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_uint(&self, fid: impl GlobalVarId) -> Option<pbuint> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Uint);
        unsafe { self.get_var_uint_unchecked(fid) }
    }

    /// 获取`uint`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_uint_unchecked(&self, fid: impl GlobalVarId) -> Option<pbuint> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetUintGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`long`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_long(&self, fid: impl GlobalVarId) -> Option<pblong> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Long);
        unsafe { self.get_var_long_unchecked(fid) }
    }

    /// 获取`long`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_long_unchecked(&self, fid: impl GlobalVarId) -> Option<pblong> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetLongGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`ulong`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_ulong(&self, fid: impl GlobalVarId) -> Option<pbulong> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Ulong);
        unsafe { self.get_var_ulong_unchecked(fid) }
    }

    /// 获取`ulong`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_ulong_unchecked(&self, fid: impl GlobalVarId) -> Option<pbulong> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetUlongGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`longlong`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_longlong(&self, fid: impl GlobalVarId) -> Option<pblonglong> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::LongLong);
        unsafe { self.get_var_longlong_unchecked(fid) }
    }

    /// 获取`longlong`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_longlong_unchecked(&self, fid: impl GlobalVarId) -> Option<pblonglong> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetLongLongGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`real`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_real(&self, fid: impl GlobalVarId) -> Option<pbreal> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Real);
        unsafe { self.get_var_real_unchecked(fid) }
    }

    /// 获取`real`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_real_unchecked(&self, fid: impl GlobalVarId) -> Option<pbreal> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetRealGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`double`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_double(&self, fid: impl GlobalVarId) -> Option<pbdouble> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Double);
        unsafe { self.get_var_double_unchecked(fid) }
    }

    /// 获取`double`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_double_unchecked(&self, fid: impl GlobalVarId) -> Option<pbdouble> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetDoubleGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`decimal`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "decimal")]
    pub fn get_var_dec(&self, fid: impl GlobalVarId) -> Option<Decimal> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Decimal);
        unsafe { self.get_var_dec_unchecked(fid) }
    }

    /// 获取`decimal`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "decimal")]
    pub unsafe fn get_var_dec_unchecked(&self, fid: impl GlobalVarId) -> Option<Decimal> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetDecGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_dec_unchecked(v))
        }
    }

    /// 获取`string`类型全局变量的引用
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    ///
    /// # Safety
    ///
    /// 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_str<'a>(&'a self, fid: impl GlobalVarId) -> Option<&'a PBStr> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::String);
        self.get_var_str_unchecked(fid)
    }

    /// 获取`string`类型全局变量的引用,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// - 类型不兼容时可能会出现未定义行为
    /// - 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_str_unchecked<'a>(&'a self, fid: impl GlobalVarId) -> Option<&'a PBStr> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetStringGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_string_unchecked(v))
        }
    }

    /// 获取`string`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_string(&self, fid: impl GlobalVarId) -> Option<PBString> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::String);
        unsafe { self.get_var_string_unchecked(fid) }
    }

    /// 获取`string`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_string_unchecked(&self, fid: impl GlobalVarId) -> Option<PBString> {
        self.get_var_str_unchecked(fid).map(|v| v.to_ucstring())
    }

    /// 获取`boolean`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_bool(&self, fid: impl GlobalVarId) -> Option<bool> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Boolean);
        unsafe { self.get_var_bool_unchecked(fid) }
    }

    /// 获取`boolean`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_bool_unchecked(&self, fid: impl GlobalVarId) -> Option<bool> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetBoolGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v.into())
        }
    }

    /// 获取`blob`类型全局变量的引用
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    ///
    /// # Safety
    ///
    /// 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_blob<'a>(&'a self, fid: impl GlobalVarId) -> Option<&'a [u8]> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Blob);
        self.get_var_blob_unchecked(fid)
    }

    /// 获取`blob`类型全局变量的引用,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// - 类型不兼容时可能会出现未定义行为
    /// - 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_blob_unchecked<'a>(&'a self, fid: impl GlobalVarId) -> Option<&'a [u8]> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetBlobGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_blob_unchecked(v))
        }
    }

    /// 获取`date`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn get_var_date(&self, fid: impl GlobalVarId) -> Option<NaiveDate> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Date);
        unsafe { self.get_var_date_unchecked(fid) }
    }

    /// 获取`date`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn get_var_date_unchecked(&self, fid: impl GlobalVarId) -> Option<NaiveDate> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetDateGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_date_unchecked(v))
        }
    }

    /// 获取`time`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn get_var_time(&self, fid: impl GlobalVarId) -> Option<NaiveTime> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Time);
        unsafe { self.get_var_time_unchecked(fid) }
    }

    /// 获取`time`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn get_var_time_unchecked(&self, fid: impl GlobalVarId) -> Option<NaiveTime> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetTimeGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_time_unchecked(v))
        }
    }

    /// 获取`datetime`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn get_var_datetime(&self, fid: impl GlobalVarId) -> Option<NaiveDateTime> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::DateTime);
        unsafe { self.get_var_datetime_unchecked(fid) }
    }

    /// 获取`datetime`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn get_var_datetime_unchecked(&self, fid: impl GlobalVarId) -> Option<NaiveDateTime> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetDateTimeGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(self.get_datetime_unchecked(v))
        }
    }

    /// 获取`char`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_char(&self, fid: impl GlobalVarId) -> Option<PBChar> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Char);
        unsafe { self.get_var_char_unchecked(fid) }
    }

    /// 获取`char`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_char_unchecked(&self, fid: impl GlobalVarId) -> Option<PBChar> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetCharGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取`byte`类型全局变量值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn get_var_byte(&self, fid: impl GlobalVarId) -> Option<pbbyte> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Byte);
        unsafe { self.get_var_byte_unchecked(fid) }
    }

    /// 获取`byte`类型全局变量值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn get_var_byte_unchecked(&self, fid: impl GlobalVarId) -> Option<pbbyte> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetByteGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(v)
        }
    }

    /// 获取对象类型全局变量的引用
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    ///
    /// # Safety
    ///
    /// 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_object<'a>(&'a self, fid: impl GlobalVarId) -> Option<Object<'a>> {
        let fid = fid.var_id(self);
        assert!(self.is_var_object(fid));
        self.get_var_object_unchecked(fid)
    }

    /// 获取对象类型全局变量的引用,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// - 类型不兼容时可能会出现未定义行为
    /// - 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_object_unchecked<'a>(&'a self, fid: impl GlobalVarId) -> Option<Object<'a>> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetObjectGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(Object::from_ptr(v, self.clone()))
        }
    }

    /// 获取数组类型全局变量的引用
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    ///
    /// # Safety
    ///
    /// 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_array<'a>(&'a self, fid: impl GlobalVarId) -> Option<Array<'a>> {
        let fid = fid.var_id(self);
        assert!(self.is_var_array(fid));
        self.get_var_array_unchecked(fid)
    }

    /// 获取数组类型全局变量的引用,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// - 类型不兼容时可能会出现未定义行为
    /// - 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_array_unchecked<'a>(&'a self, fid: impl GlobalVarId) -> Option<Array<'a>> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetArrayGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(Array::from_ptr(v, self.is_var_object(fid), self.clone()))
        }
    }

    /// 获取`any`类型全局变量的引用
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    ///
    /// # Safety
    ///
    /// 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_any<'a>(&'a self, fid: impl GlobalVarId) -> Option<Value<'a>> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Any);
        self.get_var_any_unchecked(fid)
    }

    /// 获取`any`类型全局变量的引用,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// - 类型不兼容时可能会出现未定义行为
    /// - 引用类型不能保证始终有效,详情请阅读[内存安全]说明
    ///
    /// [内存安全]: ./index.html#内存安全
    pub unsafe fn get_var_any_unchecked<'a>(&'a self, fid: impl GlobalVarId) -> Option<Value<'a>> {
        let mut is_null = Default::default();
        let v = ffi::pbsession_GetPBAnyGlobalVar(self.ptr, fid.var_id(self), &mut is_null);
        if is_null == true {
            None
        } else {
            Some(Value::from_ptr(v, self.clone()))
        }
    }

    /// 设置全局变量的值为NULL
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    pub fn set_var_to_null(&self, fid: impl GlobalVarId) {
        unsafe { ffi::pbsession_SetGlobalVarToNull(self.ptr, fid.var_id(self)) }
    }

    /// 设置`int`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_int(&mut self, fid: impl GlobalVarId, value: pbint) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Int);
        unsafe { ffi::pbsession_SetIntGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`int`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_int_unchecked(&mut self, fid: impl GlobalVarId, value: pbint) -> Result<()> {
        ffi::pbsession_SetIntGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`uint`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_uint(&mut self, fid: impl GlobalVarId, value: pbuint) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Uint);
        unsafe { ffi::pbsession_SetUintGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`uint`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_uint_unchecked(&mut self, fid: impl GlobalVarId, value: pbuint) -> Result<()> {
        ffi::pbsession_SetUintGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`long`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_long(&mut self, fid: impl GlobalVarId, value: pblong) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Long);
        unsafe { ffi::pbsession_SetLongGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`long`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_long_unchecked(&mut self, fid: impl GlobalVarId, value: pblong) -> Result<()> {
        ffi::pbsession_SetLongGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`ulong`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_ulong(&mut self, fid: impl GlobalVarId, value: pbulong) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Ulong);
        unsafe { ffi::pbsession_SetUlongGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`ulong`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_ulong_unchecked(&mut self, fid: impl GlobalVarId, value: pbulong) -> Result<()> {
        ffi::pbsession_SetUlongGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`longlong`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_longlong(&mut self, fid: impl GlobalVarId, value: pblonglong) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::LongLong);
        unsafe { ffi::pbsession_SetLongLongGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`longlong`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_longlong_unchecked(
        &mut self,
        fid: impl GlobalVarId,
        value: pblonglong
    ) -> Result<()> {
        ffi::pbsession_SetLongLongGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`real`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_real(&mut self, fid: impl GlobalVarId, value: pbreal) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Real);
        unsafe { ffi::pbsession_SetRealGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`real`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_real_unchecked(&mut self, fid: impl GlobalVarId, value: pbreal) -> Result<()> {
        ffi::pbsession_SetRealGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`double`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_double(&mut self, fid: impl GlobalVarId, value: pbdouble) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Double);
        unsafe { ffi::pbsession_SetDoubleGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`double`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_double_unchecked(&mut self, fid: impl GlobalVarId, value: pbdouble) -> Result<()> {
        ffi::pbsession_SetDoubleGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`decimal`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "decimal")]
    pub fn set_var_dec(&mut self, fid: impl GlobalVarId, value: Decimal) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Decimal);
        unsafe { ffi::pbsession_SetDecGlobalVar(self.ptr, fid, self.new_pbdec(value)).into() }
    }

    /// 设置`decimal`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "decimal")]
    pub unsafe fn set_var_dec_unchecked(&mut self, fid: impl GlobalVarId, value: Decimal) -> Result<()> {
        ffi::pbsession_SetDecGlobalVar(self.ptr, fid.var_id(self), self.new_pbdec(value)).into()
    }

    /// 设置`string`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_str(&mut self, fid: impl GlobalVarId, value: impl AsPBStr) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::String);
        unsafe { ffi::pbsession_SetStringGlobalVar(self.ptr, fid, value.as_pbstr().as_ptr()).into() }
    }

    /// 设置`string`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_str_unchecked(&mut self, fid: impl GlobalVarId, value: impl AsPBStr) -> Result<()> {
        ffi::pbsession_SetStringGlobalVar(self.ptr, fid.var_id(self), value.as_pbstr().as_ptr()).into()
    }

    /// 设置`boolean`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_bool(&mut self, fid: impl GlobalVarId, value: bool) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Boolean);
        unsafe { ffi::pbsession_SetBoolGlobalVar(self.ptr, fid, value.into()).into() }
    }

    /// 设置`boolean`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_bool_unchecked(&mut self, fid: impl GlobalVarId, value: bool) -> Result<()> {
        ffi::pbsession_SetBoolGlobalVar(self.ptr, fid.var_id(self), value.into()).into()
    }

    /// 设置`blob`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_blob(&mut self, fid: impl GlobalVarId, value: impl AsRef<[u8]>) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Blob);
        unsafe { ffi::pbsession_SetBlobGlobalVar(self.ptr, fid, self.new_pbblob(value)).into() }
    }

    /// 设置`blob`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_blob_unchecked(
        &mut self,
        fid: impl GlobalVarId,
        value: impl AsRef<[u8]>
    ) -> Result<()> {
        let value = value.as_ref();
        if value.is_empty() {
            return Err(PBXRESULT::E_OUTOF_MEMORY);
        }
        ffi::pbsession_SetBlobGlobalVar(self.ptr, fid.var_id(self), self.new_pbblob(value)).into()
    }

    /// 设置`date`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn set_var_date(&mut self, fid: impl GlobalVarId, value: NaiveDate) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Date);
        unsafe { ffi::pbsession_SetDateGlobalVar(self.ptr, fid, self.new_pbdate(value)).into() }
    }

    /// 设置`date`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn set_var_date_unchecked(&mut self, fid: impl GlobalVarId, value: NaiveDate) -> Result<()> {
        ffi::pbsession_SetDateGlobalVar(self.ptr, fid.var_id(self), self.new_pbdate(value)).into()
    }

    /// 设置`time`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn set_var_time(&mut self, fid: impl GlobalVarId, value: NaiveTime) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Time);
        unsafe { ffi::pbsession_SetTimeGlobalVar(self.ptr, fid, self.new_pbtime(value)).into() }
    }

    /// 设置`time`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn set_var_time_unchecked(&mut self, fid: impl GlobalVarId, value: NaiveTime) -> Result<()> {
        ffi::pbsession_SetTimeGlobalVar(self.ptr, fid.var_id(self), self.new_pbtime(value)).into()
    }

    /// 设置`datetime`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    #[cfg(feature = "datetime")]
    pub fn set_var_datetime(&mut self, fid: impl GlobalVarId, value: NaiveDateTime) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::DateTime);
        unsafe { ffi::pbsession_SetDateTimeGlobalVar(self.ptr, fid, self.new_pbdatetime(value)).into() }
    }

    /// 设置`datetime`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    #[cfg(feature = "datetime")]
    pub unsafe fn set_var_datetime_unchecked(
        &mut self,
        fid: impl GlobalVarId,
        value: NaiveDateTime
    ) -> Result<()> {
        ffi::pbsession_SetDateTimeGlobalVar(self.ptr, fid.var_id(self), self.new_pbdatetime(value)).into()
    }

    /// 设置`char`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_char(&mut self, fid: impl GlobalVarId, value: PBChar) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Char);
        unsafe { ffi::pbsession_SetCharGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`char`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_char_unchecked(&mut self, fid: impl GlobalVarId, value: PBChar) -> Result<()> {
        ffi::pbsession_SetCharGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置`byte`类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_byte(&mut self, fid: impl GlobalVarId, value: pbbyte) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.get_var_type(fid) == ValueType::Byte);
        unsafe { ffi::pbsession_SetByteGlobalVar(self.ptr, fid, value).into() }
    }

    /// 设置`byte`类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_byte_unchecked(&mut self, fid: impl GlobalVarId, value: pbbyte) -> Result<()> {
        ffi::pbsession_SetByteGlobalVar(self.ptr, fid.var_id(self), value).into()
    }

    /// 设置对象类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_object(&mut self, fid: impl GlobalVarId, value: &Object) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.is_var_object(fid));
        unsafe { ffi::pbsession_SetObjectGlobalVar(self.ptr, fid, value.as_ptr()).into() }
    }

    /// 设置对象类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_object_unchecked(&mut self, fid: impl GlobalVarId, value: &Object) -> Result<()> {
        ffi::pbsession_SetObjectGlobalVar(self.ptr, fid.var_id(self), value.as_ptr()).into()
    }

    /// 设置数组类型全局变量的值
    ///
    /// # Panics
    ///
    /// 访问不存在的变量或类型不匹配时会触发Panic
    pub fn set_var_array(&mut self, fid: impl GlobalVarId, value: &Array) -> Result<()> {
        let fid = fid.var_id(self);
        assert!(self.is_var_array(fid));
        unsafe { ffi::pbsession_SetArrayGlobalVar(self.ptr, fid, value.as_ptr()).into() }
    }

    /// 设置数组类型全局变量的值,不检查类型
    ///
    /// # Panics
    ///
    /// 访问不存在的变量时会触发Panic
    ///
    /// # Safety
    ///
    /// 类型不兼容时可能会出现未定义行为
    pub unsafe fn set_var_array_unchecked(&mut self, fid: impl GlobalVarId, value: &Array) -> Result<()> {
        ffi::pbsession_SetArrayGlobalVar(self.ptr, fid.var_id(self), value.as_ptr()).into()
    }
}

/*
    Method calling
*/

/// 函数名抽象
pub trait AsMethodName {
    fn as_method_name(&self) -> (Cow<'_, PBStr>, Cow<'_, PBStr>);
}

impl<T: AsPBStr> AsMethodName for T {
    #[inline]
    fn as_method_name(&self) -> (Cow<'_, PBStr>, Cow<'_, PBStr>) { (self.as_pbstr(), "".as_pbstr()) }
}

impl<T: AsPBStr, S: AsPBStr> AsMethodName for (T, S) {
    #[inline]
    fn as_method_name(&self) -> (Cow<'_, PBStr>, Cow<'_, PBStr>) {
        let (name, sign) = self;
        (name.as_pbstr(), sign.as_pbstr())
    }
}

/// 全局函数ID
#[derive(Clone, Copy)]
pub struct GlobalFunctionId {
    pub(crate) cls: pbclass,
    pub(crate) mid: MethodId
}

/// 全局函数ID抽象
pub trait AsGlobalFunctionId {
    fn as_mid(&self, session: &Session) -> Result<GlobalFunctionId>;
}

impl<T: AsMethodName> AsGlobalFunctionId for T {
    #[inline]
    fn as_mid(&self, session: &Session) -> Result<GlobalFunctionId> {
        session.get_function_id(self.as_method_name()).ok_or(PBXRESULT::E_INVALID_METHOD_ID)
    }
}
impl AsGlobalFunctionId for GlobalFunctionId {
    #[inline]
    fn as_mid(&self, _session: &Session) -> Result<GlobalFunctionId> { Ok(*self) }
}
impl AsGlobalFunctionId for Option<GlobalFunctionId> {
    #[inline]
    fn as_mid(&self, _session: &Session) -> Result<GlobalFunctionId> {
        self.ok_or(PBXRESULT::E_INVALID_METHOD_ID)
    }
}

impl Session {
    /// 获取用户定义全局函数ID
    ///
    /// # Examples
    ///
    /// ```
    /// let fid = session.get_user_function_id("gf_test").unwrap();
    /// let invoker = session.begin_invoke_function(fid).unwrap();
    /// invoker.invoke();
    /// ```
    pub fn get_user_function_id(&self, name: impl AsMethodName) -> Option<GlobalFunctionId> {
        let (name, sign) = name.as_method_name();
        if let Some(group) = self.find_group(name.as_ref(), GroupType::Function) {
            self.find_class(group, name.as_ref()).and_then(|cls| {
                self.get_method_id(cls, name.as_ref(), RoutineType::Function, sign, true).map(|mid| {
                    GlobalFunctionId {
                        cls,
                        mid
                    }
                })
            })
        } else {
            None
        }
    }

    /// 获取系统全局函数ID
    ///
    /// # Examples
    ///
    /// ```
    /// let fid = session.get_system_function_id(("MessageBox","ISS")).unwrap();
    /// let invoker = session.begin_invoke_function(fid).unwrap();
    /// invoker.arg(0).set_str("title");
    /// invoker.arg(1).set_str("content");
    /// invoker.invoke();
    /// ```
    pub fn get_system_function_id(&self, name: impl AsMethodName) -> Option<GlobalFunctionId> {
        let (name, sign) = name.as_method_name();
        self.find_class(self.get_system_group(), "SystemFunctions").and_then(|cls| {
            self.get_method_id(cls, name, RoutineType::Function, sign, true).map(|mid| {
                GlobalFunctionId {
                    cls,
                    mid
                }
            })
        })
    }

    /// 获取任意全局函数ID
    ///
    /// # Examples
    ///
    /// ```
    /// let fid = session.get_function_id(("MessageBox","ISS")).unwrap();
    /// let invoker = session.begin_invoke_function(fid).unwrap();
    /// invoker.arg(0).set_str("title");
    /// invoker.arg(1).set_str("content");
    /// invoker.invoke();
    /// ```
    pub fn get_function_id(&self, name: impl AsMethodName) -> Option<GlobalFunctionId> {
        let (name, sign) = name.as_method_name();
        self.get_user_function_id((name.as_ref(), sign.as_ref()))
            .or_else(|| self.get_system_function_id((name, sign)))
    }

    /// 调用全局函数
    ///
    /// # Examples
    ///
    /// ```
    /// let rv: pbint = session.invoke_function(("MessageBox","ISS"),pbargs!["title","content"]).unwrap();
    /// ```
    pub fn invoke_function<F, R>(&self, mid: impl AsGlobalFunctionId, arg_cb: F) -> Result<R>
    where
        F: FnOnce(Arguments) -> Result<()>,
        R: FromValueOwned
    {
        let invoker = self.begin_invoke_function(mid)?;
        arg_cb(invoker.args())?;
        let rv = invoker.invoke()?;
        R::from_value(Some(rv))
    }

    /// 初始化全局函数调用上下文
    ///
    /// # Examples
    ///
    /// ```
    /// let invoker = session.begin_invoke_function(("MessageBox","ISS")).unwrap();
    /// invoker.arg(0).set_str("title");
    /// invoker.arg(1).set_str("content");
    /// invoker.invoke();
    /// ```
    pub fn begin_invoke_function<'a>(
        &'a self,
        mid: impl AsGlobalFunctionId
    ) -> Result<Invoker<GlobalFunction<'a>>> {
        let mid = mid.as_mid(self)?;
        let ci = unsafe { CallInfo::new(mid.cls, mid.mid, self.clone())? };
        Ok(Invoker::<GlobalFunction>::new(GlobalFunction::new(mid.cls), ci))
    }

    pub(crate) fn get_method_id(
        &self,
        cls: pbclass,
        methodName: impl AsPBStr,
        rt: RoutineType,
        signature: impl AsPBStr,
        publicOnly: bool
    ) -> Option<MethodId> {
        unsafe {
            let mid = ffi::pbsession_GetMethodID(
                self.ptr,
                cls,
                methodName.as_pbstr().as_ptr(),
                rt,
                signature.as_pbstr().as_ptr(),
                publicOnly.into()
            );
            if mid.is_undefined() {
                None
            } else {
                Some(mid)
            }
        }
    }
    pub(crate) fn find_matching_function(
        &self,
        cls: pbclass,
        methodName: impl AsPBStr,
        rt: RoutineType,
        readableSignature: impl AsPBStr
    ) -> Option<MethodId> {
        unsafe {
            let mid = ffi::pbsession_FindMatchingFunction(
                self.ptr,
                cls,
                methodName.as_pbstr().as_ptr(),
                rt,
                readableSignature.as_pbstr().as_ptr()
            );
            if mid.is_undefined() {
                None
            } else {
                Some(mid)
            }
        }
    }
    pub(crate) fn get_method_id_by_event_id(&self, cls: pbclass, eventID: impl AsPBStr) -> Option<MethodId> {
        unsafe {
            let mid = ffi::pbsession_GetMethodIDByEventID(self.ptr, cls, eventID.as_pbstr().as_ptr());
            if mid.is_undefined() {
                None
            } else {
                Some(mid)
            }
        }
    }
}

/// 拥有所有权的Session对象
///
/// 此对象由[`VM`]创建,`drop`时会释放会话
pub struct OwnedSession<'vm> {
    session: Session,
    _marker: PhantomData<&'vm ()>
}

impl<'vm> OwnedSession<'vm> {
    pub(crate) unsafe fn from_ptr(ptr: pbsession) -> OwnedSession<'vm> {
        OwnedSession {
            session: Session::from_ptr(ptr),
            _marker: PhantomData
        }
    }

    /// 设置`DebugTrace`文件
    pub fn set_debug_trace(&self, traceFile: impl AsPBStr) {
        unsafe { ffi::pbsession_SetDebugTrace(self.session.ptr, traceFile.as_pbstr().as_ptr()) }
    }

    /// 释放会话
    pub fn release(self) {}
}

impl Drop for OwnedSession<'_> {
    fn drop(&mut self) { unsafe { ffi::pbsession_Release(self.session.ptr) } }
}

impl Deref for OwnedSession<'_> {
    type Target = Session;
    fn deref(&self) -> &Self::Target { &self.session }
}

/// 栈帧
///
/// 当**直接**从Rust端调用PB代码时一般需要创建栈帧来释放调用阶段产生的临时资源,比如创建的对象
///
/// # Examples
///
/// ```
/// //创建栈帧
/// let frame = LocalFrame::new(&session);
/// //手动退出栈帧
/// //pop调用不是必须的,变量drop时会自动退出
/// frame.pop();
/// ```
#[must_use]
pub struct LocalFrame<'session> {
    session: &'session Session
}

impl<'session> LocalFrame<'session> {
    /// 创建栈帧
    pub fn new(session: &Session) -> LocalFrame {
        unsafe { ffi::pbsession_PushLocalFrame(session.ptr) }
        LocalFrame {
            session
        }
    }
    /// 手动退出栈帧
    pub fn pop(self) {}
}

impl<'session> Drop for LocalFrame<'session> {
    fn drop(&mut self) { unsafe { ffi::pbsession_PopLocalFrame(self.session.ptr) } }
}

/*
thread_local! {
    static SESSION: Cell<Option<Session>> = Cell::new(None)
}

/// 设置线程当前SESSION对象
pub(crate) fn set_current_session(session: Session) {
    SESSION.with(|s| {
        s.set(Some(session));
    });
}

/// 线程当前SESSION对象
pub fn current_session() -> Option<Session> { SESSION.with(|s| s.get()) }
*/