hostfxr-sys 0.13.0

FFI bindings for hostfxr.
Documentation
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
#![warn(clippy::pedantic, clippy::cargo, unsafe_op_in_unsafe_fn)]
#![allow(
    clippy::missing_safety_doc,
    clippy::missing_errors_doc,
    clippy::missing_panics_doc,
    clippy::module_name_repetitions,
    clippy::multiple_crate_versions,
    clippy::doc_markdown,
    non_camel_case_types,
    dead_code
)]
#![cfg_attr(feature = "doc-cfg", feature(doc_cfg))]

/*!

FFI bindings for [hostfxr](https://github.com/dotnet/runtime/blob/main/docs/design/features/host-components.md#components-of-the-hosting).

## Related crates
- [nethost-sys](https://crates.io/crates/nethost-sys) - bindings for the nethost library.
- [coreclr-hosting-shared](https://crates.io/crates/coreclr-hosting-shared) - shared bindings between this crate and [nethost-sys](https://crates.io/crates/nethost-sys).
- [netcorehost](https://crates.io/crates/netcorehost) - rusty wrapper over the nethost and hostfxr libraries.

## Additional Information
- [Hosting layer APIs](https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/hosting-layer-apis.md)
- [Native hosting](https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/native-hosting.md#runtime-properties)
- [Write a custom .NET Core host to control the .NET runtime from your native code](https://docs.microsoft.com/en-us/dotnet/core/tutorials/netcore-hosting)

## License
Licensed under the MIT license ([LICENSE](https://github.com/OpenByteDev/hostfxr-sys/blob/master/LICENSE) or <http://opensource.org/licenses/MIT>)
*/

pub use dlopen2;

use core::{ffi::c_void, mem};
use coreclr_hosting_shared::{char_t, size_t};

/// Signifies that the target method is marked with the [`UnmanagedCallersOnlyAttribute`].
/// This means that the name alone can identify the target method.
///
/// [`UnmanagedCallersOnlyAttribute`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute
#[cfg(feature = "net5_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))]
pub const UNMANAGED_CALLERS_ONLY_METHOD: *const char_t = usize::MAX as *const _;

/// Seperator char used to seperate a list of paths in a string.
#[cfg(windows)]
pub const PATH_LIST_SEPARATOR: char_t = b';' as char_t;
/// Seperator char used to seperate a list of paths in a string.
#[cfg(not(windows))]
#[allow(clippy::cast_possible_wrap)]
pub const PATH_LIST_SEPARATOR: char_t = b':' as char_t;

#[cfg(feature = "netcore3_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
#[cfg_attr(feature = "enum-map", derive(enum_map::Enum))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
/// Enum representing the type of runtime functionality requested with `hostfxr_get_runtime_delegate`.
pub enum hostfxr_delegate_type {
    hdt_com_activation = 0,
    /// IJW entry-point
    hdt_load_in_memory_assembly = 1,
    /// WinRT activation entry-point
    #[cfg(all(feature = "netcore3_0", not(feature = "net5_0")))]
    #[cfg_attr(
        feature = "doc-cfg",
        doc(cfg(all(feature = "netcore3_0", not(feature = "net5_0"))))
    )]
    hdt_winrt_activation = 2,
    hdt_com_register = 3,
    hdt_com_unregister = 4,
    /// Entry point which loads an assembly (with dependencies) and returns a function pointer for a specified static method.
    hdt_load_assembly_and_get_function_pointer = 5,
    /// Entry-point which finds a managed method and returns a function pointer to it.
    #[cfg(feature = "net5_0")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))]
    hdt_get_function_pointer = 6,
    /// Entry-point which loads an assembly by its path.
    #[cfg(feature = "net8_0")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net8_0")))]
    hdt_load_assembly = 7,
    /// Entry-point which loads an assembly from a byte array.
    #[cfg(feature = "net8_0")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net8_0")))]
    hdt_load_assembly_bytes = 8,
}

/// Error reporting function signature.
#[cfg(feature = "netcore3_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
pub type hostfxr_error_writer_fn = extern "C" fn(message: *const char_t);

/// Flag constants for `hostfxr_resolve_sdk2`.
#[allow(non_upper_case_globals)]
#[cfg(feature = "netcore2_1")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
#[cfg_attr(feature = "enum-map", derive(enum_map::Enum))]
#[repr(i32)]
#[non_exhaustive]
pub enum hostfxr_resolve_sdk2_flags_t {
    none = 0x0,
    disallow_prerelease = 0x1,
}

/// Possible keys for values passed to the callback in `hostfxr_resolve_sdk2`.
#[cfg(feature = "netcore2_1")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
#[cfg_attr(feature = "enum-map", derive(enum_map::Enum))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum hostfxr_resolve_sdk2_result_key_t {
    resolved_sdk_dir = 0,
    global_json_path = 1,
    requested_version = 2,
    global_json_state = 3,
}

/// Possible values for value in `hostfxr_resolve_sdk2_result_fn` when key is `global_json_state`.
#[cfg(feature = "netcore2_1")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
pub mod hostfxr_resolve_sdk2_global_json_state {
    // from https://github.com/dotnet/runtime/blob/59a29ee6827ba65477dc8b06132697258ef9c58f/src/native/corehost/fxr/hostfxr.cpp#L185
    pub const NOT_FOUND: &str = "not_found";
    pub const VALID: &str = "valid";
    pub const INVALID_JSON: &str = "invalid_json";
    pub const INVALID_DATA: &str = "invalid_data";
}

/// Result callback signature for `hostfxr_resolve_sdk2`.
#[cfg(feature = "netcore2_1")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
pub type hostfxr_resolve_sdk2_result_fn =
    extern "C" fn(key: hostfxr_resolve_sdk2_result_key_t, value: *const char_t);

/// Result callback signature for `hostfxr_get_available_sdks`.
#[cfg(feature = "netcore2_1")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
pub type hostfxr_get_available_sdks_result_fn =
    extern "C" fn(sdk_count: i32, sdk_dirs: *const *const char_t);

/// Result callback signature for `hostfxr_get_dotnet_environment_info`.
#[cfg(all(feature = "net6_0", feature = "undocumented"))]
#[cfg_attr(
    feature = "doc-cfg",
    doc(cfg(all(feature = "net6_0", feature = "undocumented")))
)]
pub type hostfxr_get_dotnet_environment_info_result_fn =
    unsafe extern "C" fn(info: *const hostfxr_dotnet_environment_info, result_context: *mut c_void);

#[cfg(all(feature = "net6_0", feature = "undocumented"))]
#[cfg_attr(
    feature = "doc-cfg",
    doc(cfg(all(feature = "net6_0", feature = "undocumented")))
)]
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct hostfxr_dotnet_environment_sdk_info {
    pub size: size_t,
    pub version: *const char_t,
    pub path: *const char_t,
}

#[cfg(all(feature = "net6_0", feature = "undocumented"))]
#[cfg_attr(
    feature = "doc-cfg",
    doc(cfg(all(feature = "net6_0", feature = "undocumented")))
)]
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct hostfxr_dotnet_environment_framework_info {
    pub size: size_t,
    pub name: *const char_t,
    pub version: *const char_t,
    pub path: *const char_t,
}

#[cfg(all(feature = "net6_0", feature = "undocumented"))]
#[cfg_attr(
    feature = "doc-cfg",
    doc(cfg(all(feature = "net6_0", feature = "undocumented")))
)]
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct hostfxr_dotnet_environment_info {
    pub size: size_t,

    pub hostfxr_version: *const char_t,
    pub hostfxr_commit_hash: *const char_t,

    pub sdk_count: size_t,
    pub sdks: *const hostfxr_dotnet_environment_sdk_info,

    pub framework_count: size_t,
    pub frameworks: *const hostfxr_dotnet_environment_framework_info,
}

/// Handle to a hostfxr context.
pub type hostfxr_handle = *const c_void;

/// Signature of delegate returned by [`hostfxr_get_runtime_delegate`] for type [`hdt_load_assembly_and_get_function_pointer`]
///
/// # Arguments
///  * `assembly_path`:
///    Fully qualified path to assembly
///  * `type_name`:
///    Assembly qualified type name
///  * `method_name`:
///    Public static method name compatible with delegateType
///  * `delegate_type_name`:
///    Assembly qualified delegate type name or [`null`](core::ptr::null()), or [`UNMANAGED_CALLERS_ONLY_METHOD`] if the method is marked with the [`UnmanagedCallersOnlyAttribute`].
///  * `load_context`:
///    Extensibility parameter (currently unused and must be 0)
///  * `reserved`:
///    Extensibility parameter (currently unused and must be 0)
///  * `delegate`:
///    Pointer where to store the function pointer result
///
/// [`hostfxr_get_runtime_delegate`]: wrapper/struct.Hostfxr.html#method.hostfxr_get_runtime_delegate
/// [`hdt_load_assembly_and_get_function_pointer`]: hostfxr_delegate_type::`hdt_load_assembly_and_get_function_pointer
/// [`UNMANAGED_CALLERS_ONLY_METHOD`]: UNMANAGED_CALLERS_ONLY_METHOD
/// [`UnmanagedCallersOnlyAttribute`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute
#[cfg(feature = "netcore3_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
pub type load_assembly_and_get_function_pointer_fn = unsafe extern "system" fn(
    assembly_path: *const char_t,
    type_name: *const char_t,
    method_name: *const char_t,
    delegate_type_name: *const char_t,
    reserved: *const c_void,
    /*out*/ delegate: *mut *const c_void,
) -> i32;

/// Signature of delegate returned by [`hostfxr_get_runtime_delegate`] for type [`hdt_get_function_pointer`]
///
/// Calling this function will find the specified type in the default load context, locate the required method on it and return a native function pointer to that method.
/// The method's signature can be specified via the delegate type name.
///
/// # Arguments
///  * `type_name`:
///    Assembly qualified type name
///  * `method_name`:
///    Public static method name compatible with delegateType
///  * `delegate_type_name`:
///    Assembly qualified delegate type name or [`null`](core::ptr::null()), or [`UNMANAGED_CALLERS_ONLY_METHOD`] if the method is marked with the [`UnmanagedCallersOnlyAttribute`].
///  * `load_context`:
///    Extensibility parameter (currently unused and must be 0)
///  * `reserved`:
///    Extensibility parameter (currently unused and must be 0)
///  * `delegate`:
///    Pointer where to store the function pointer result
///
/// [`hdt_get_function_pointer`]: hostfxr_delegate_type::hdt_get_function_pointer
/// [`hostfxr_get_runtime_delegate`]: wrapper/struct.Hostfxr.html#method.hostfxr_get_runtime_delegate
/// [`UNMANAGED_CALLERS_ONLY_METHOD`]: crate::UNMANAGED_CALLERS_ONLY_METHOD
/// [`UnmanagedCallersOnlyAttribute`]: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.unmanagedcallersonlyattribute
#[cfg(feature = "net5_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net5_0")))]
pub type get_function_pointer_fn = unsafe extern "system" fn(
    type_name: *const char_t,
    method_name: *const char_t,
    delegate_type_name: *const char_t,
    load_context: *const c_void,
    reserved: *const c_void,
    /*out*/ delegate: *mut *const c_void,
) -> i32;

/// Signature of delegate returned by [`load_assembly_and_get_function_pointer_fn`] when `delegate_type_name == null` (default)
#[cfg(feature = "netcore3_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
pub type component_entry_point_fn = unsafe extern "system" fn(*const c_void, i32) -> i32;

/// Signature of delegate returned by [`hostfxr_get_runtime_delegate`] for type [`hdt_load_assembly`].
///
/// Calling this function will load the specified assembly in the default load context.
/// It uses [`AssemblyDependencyResolver`] to register additional dependency resolution for the load context.
///
/// # Arguments
///  * `assembly_path`:
///    Path to the assembly to load - requirements match the assemblyPath parameter of [`AssemblyLoadContext.LoadFromAssemblyPath`].
///    This path will also be used for dependency resolution via any `.deps.json` corresponding to the assembly.
///  * `load_context`:
///    The load context that will be used to load the assembly.
///    For .NET 8 this parameter must be [`null`](core::ptr::null()) and the API will only load the assembly in the default load context.
///  * `reserved`:
///    Parameter reserved for future extensibility, currently unused and must be [`null`](core::ptr::null()).
///
/// [`hdt_load_assembly`]: hostfxr_delegate_type::hdt_load_assembly
/// [`hostfxr_get_runtime_delegate`]: wrapper/struct.Hostfxr.html#method.hostfxr_get_runtime_delegate
/// [`AssemblyDependencyResolver`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblydependencyresolver
/// [`AssemblyLoadContext.LoadFromAssemblyPath`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext.loadfromassemblypath
#[cfg(feature = "net8_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net8_0")))]
pub type load_assembly_fn = unsafe extern "system" fn(
    assembly_path: *const char_t,
    load_context: *const c_void,
    reserved: *const c_void,
) -> i32;

/// Signature of delegate returned by [`hostfxr_get_runtime_delegate`] for type [`hdt_load_assembly_bytes`]
///
/// Calling this function will load the specified assembly in the default load context.
/// It does not provide a mechanism for registering additional dependency resolution, as mechanisms like `.deps.json` and [`AssemblyDependencyResolver`] are file-based.
/// Dependencies can be pre-loaded (for example, via a previous call to this function) or the specified assembly can explicitly register its own resolution logic (for example, via the [`AssemblyLoadContext.Resolving`] event).
/// It uses [`AssemblyDependencyResolver`] to register additional dependency resolution for the load context.
///
/// # Arguments
///  * `assembly_path`:
///    Path to the assembly to load - requirements match the assemblyPath parameter of [`AssemblyLoadContext.LoadFromAssemblyPath`].
///    This path will also be used for dependency resolution via any `.deps.json` corresponding to the assembly.
///  * `load_context`:
///    The load context that will be used to load the assembly.
///    For .NET 8 this parameter must be [`null`](core::ptr::null()) and the API will only load the assembly in the default load context.
///  * `reserved`:
///    Parameter reserved for future extensibility, currently unused and must be [`null`](core::ptr::null()).
///
/// [`hdt_load_assembly_bytes`]: hostfxr_delegate_type::hdt_load_assembly_bytes
/// [`hostfxr_get_runtime_delegate`]: wrapper/struct.Hostfxr.html#method.hostfxr_get_runtime_delegate
/// [`AssemblyDependencyResolver`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblydependencyresolver
/// [`AssemblyLoadContext.Resolving`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext.resolving?view=net-7.0
/// [`AssemblyLoadContext.LoadFromAssemblyPath`]: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext.loadfromassemblypath
#[cfg(feature = "net8_0")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "net8_0")))]
pub type load_assembly_bytes_fn = unsafe extern "system" fn(
    assembly_bytes: *const u8,
    assembly_bytes_len: usize,
    symbols_bytes: *const u8,
    symbols_bytes_len: usize,
    load_context: *const c_void,
    reserved: *const c_void,
) -> i32;

/// A structure that stores parameters which are common to all forms of initialization.
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct hostfxr_initialize_parameters {
    /// The size of the structure.
    /// This is used for versioning.
    /// Should be set to `mem::size_of::<hostfxr_initialize_parameters>()`.
    pub size: size_t,
    /// Path to the native host (typically the `.exe`).
    /// This value is not used for anything by the hosting components.
    /// It's just passed to the CoreCLR as the path to the executable.
    /// It can point to a file which is not executable itself, if such file doesn't exist
    /// (for example in COM activation scenarios this points to the `comhost.dll`).
    /// This is used by PAL (Platform Abstraction Layer) to initialize internal command line structures, process name and so on.
    pub host_path: *const char_t,
    /// Path to the root of the .NET Core installation in use.
    /// This typically points to the install location from which the hostfxr has been loaded.
    /// For example on Windows this would typically point to `C:\Program Files\dotnet`.
    /// The path is used to search for shared frameworks and potentially SDKs.
    pub dotnet_root: *const char_t,
}

impl hostfxr_initialize_parameters {
    /// Creates a new instance with the given `host_path`.
    /// The `size` field is set accordingly to the size of the struct and `dotnet_root` to [`core::ptr::null()`].
    #[must_use]
    pub fn with_host_path(host_path: *const char_t) -> Self {
        Self {
            size: mem::size_of::<Self>(),
            host_path,
            dotnet_root: core::ptr::null(),
        }
    }
    /// Creates a new instance with the given `dotnet_root`.
    /// The `size` field is set accordingly to the size of the struct and `host_path` to [`core::ptr::null()`].
    #[must_use]
    pub fn with_dotnet_root(dotnet_root: *const char_t) -> Self {
        Self {
            size: mem::size_of::<Self>(),
            host_path: core::ptr::null(),
            dotnet_root,
        }
    }
}

macro_rules! derive_apis {
    (
        $( #[$struct_attrs:meta] )*
        $visibility:vis struct $name:ident {
        $(
            $( #[$field_attrs:meta] )*
            $field:ident : $field_type:ty,
        )*
    }) => {
        /// [`dlopen2::symbor`] abstraction for the hostfxr library.
        #[cfg(feature = "symbor")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "symbor")))]
        $visibility mod symbor {
            #[allow(unused_imports)]
            use super::*;
            use dlopen2::symbor::{Symbol, SymBorApi};

            /// [`dlopen2::symbor`] abstraction for the hostfxr library.
            $( #[$struct_attrs] )*
            #[derive(SymBorApi)]
            $visibility struct $name <'lib> {
                // ensures that 'lib is used
                #[cfg(not(feature = "netcore1_0"))]
                _dummy: Option<Symbol<'lib, fn()>>,

                $(
                    $( #[$field_attrs] )*
                    pub $field : Symbol<'lib, $field_type>
                ),*
            }
        }

        /// [`dlopen2::symbor`] abstraction for the hostfxr library, with all symbols marked as optional.
        #[cfg(all(feature = "symbor", feature = "optional-apis"))]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(all(feature = "symbor", feature = "optional-apis"))))]
        $visibility mod symbor_option {
            #[allow(unused_imports)]
            use super::*;
            use dlopen2::symbor::{Symbol, SymBorApi};

            /// [`dlopen2::symbor`] abstraction for the hostfxr library, with all symbols marked as optional.
            $( #[$struct_attrs] )*
            #[derive(SymBorApi)]
            $visibility struct $name <'lib> {
                // ensures that 'lib is used
                #[cfg(not(feature = "netcore1_0"))]
                _dummy: Option<Symbol<'lib, fn()>>,

                $(
                    $( #[$field_attrs] )*
                    pub $field : Option<Symbol<'lib, $field_type>>
                ),*
            }
        }

        /// [`dlopen2::wrapper`] abstraction for the hostfxr library.
        #[cfg(feature = "wrapper")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "wrapper")))]
        $visibility mod wrapper {
            #[allow(unused_imports)]
            use super::*;
            use dlopen2::wrapper::WrapperApi;

            /// [`dlopen2::wrapper`] abstraction for the hostfxr library.
            $( #[$struct_attrs] )*
            #[derive(WrapperApi)]
            $visibility struct $name {
                $(
                    $( #[$field_attrs] )*
                    $field : $field_type
                ),*
            }
        }

        /// [`dlopen2::wrapper`] abstraction for the hostfxr library, with all symbols marked as optional.
        #[cfg(all(feature = "wrapper", feature = "optional-apis"))]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(all(feature = "wrapper", feature = "optional-apis"))))]
        $visibility mod wrapper_option {
            #[allow(unused_imports)]
            use super::*;
            use dlopen2::wrapper::WrapperApi;

            /// [`dlopen2::wrapper`] abstraction for the hostfxr library, with all symbols marked as optional.
            $( #[$struct_attrs] )*
            #[derive(WrapperApi)]
            $visibility struct $name {
                $(
                    $( #[$field_attrs] )*
                    $field : Option<$field_type>
                ),*
            }
        }
    }
}

derive_apis! {
    #[allow(clippy::struct_field_names)]
    pub struct Hostfxr {
        /// Run an application.
        ///
        /// # Arguments
        ///  * `argv` - command-line arguments
        ///
        /// This function does not return until the application completes execution.
        /// It will shutdown CoreCLR after the application executes.
        /// If the application is successfully executed, this value will return the exit code of the application. Otherwise, it will return an error code indicating the failure.
        #[cfg(feature = "netcore1_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore1_0")))]
        hostfxr_main: unsafe extern "C" fn(argc: i32, argv: *const *const char_t) -> i32,

        /// Determines the directory location of the SDK accounting for
        /// `global.json` and multi-level lookup policy.
        ///
        /// Invoked via MSBuild SDK resolver to locate SDK props and targets
        /// from an msbuild other than the one bundled by the CLI.
        ///
        /// # Arguments
        ///  * `exe_dir`
        ///      The main directory where SDKs are located in `sdk\[version]`
        ///      sub-folders. Pass the directory of a dotnet executable to
        ///      mimic how that executable would search in its own directory.
        ///      It is also valid to pass nullptr or empty, in which case
        ///      multi-level lookup can still search other locations if
        ///      it has not been disabled by the user's environment.
        ///  * `working_dir`
        ///      The directory where the search for `global.json` (which can
        ///      control the resolved SDK version) starts and proceeds
        ///      upwards.
        ///  * `buffer`
        ///      The buffer where the resolved SDK path will be written.
        ///  * `buffer_size`
        ///      The size of the buffer argument in [`char_t`] units.
        ///
        /// # Return value:
        ///  * `<0` - Invalid argument
        ///  * `0`  - SDK could not be found.
        ///  * `>0` - The number of characters (including null terminator)
        ///        required to store the located SDK.
        ///
        /// If resolution succeeds and the positive return value is less than
        /// or equal to `buffer_size` (i.e. the the buffer is large enough),
        /// then the resolved SDK path is copied to the buffer and null
        /// terminated. Otherwise, no data is written to the buffer.
        #[deprecated(note = "Use `hostfxr_resolve_sdk2` instead.")]
        #[cfg(feature = "netcore2_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_0")))]
        hostfxr_resolve_sdk: unsafe extern "C" fn(
            exe_dir: *const char_t,
            working_dir: *const char_t,
            buffer: *mut char_t,
            buffer_size: i32,
        ) -> i32,

        /// Run an application.
        ///
        /// # Arguments
        ///  * `argv`
        ///     command-line arguments
        ///  * `host_path`
        ///     path to the host application
        ///  * `dotnet_root`
        ///     path to the .NET Core installation root
        ///  * `app_path`
        ///     path to the application to run
        ///
        /// This function does not return until the application completes execution.
        /// It will shutdown CoreCLR after the application executes.
        /// If the application is successfully executed, this value will return the exit code of the application. Otherwise, it will return an error code indicating the failure.
        #[cfg(feature = "netcore2_1")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
        hostfxr_main_startupinfo: unsafe extern "C" fn(
            argc: i32,
            argv: *const *const char_t,
            host_path: *const char_t,
            dotnet_root: *const char_t,
            app_path: *const char_t,
        ) -> i32,

        #[cfg(all(feature = "netcore2_1", feature = "undocumented"))]
        #[cfg_attr(
            feature = "doc-cfg",
            doc(cfg(all(feature = "netcore2_1", feature = "undocumented")))
        )]
        hostfxr_main_bundle_startupinfo: unsafe extern "C" fn(
            argc: i32,
            argv: *const *const char_t,
            host_path: *const char_t,
            dotnet_root: *const char_t,
            app_path: *const char_t,
            bundle_header_offset: i64,
        ) -> i32,

        /// Determine the directory location of the SDK, accounting for `global.json` and multi-level lookup policy.
        ///
        /// # Arguments
        ///  * `exe_dir` main directory where SDKs are located in `sdk\[version]` sub-folders.
        ///  * `working_dir` directory where the search for `global.json` will start and proceed upwards
        ///  * `flags` flags that influence resolution:
        ///         `disallow_prerelease` - do not allow resolution to return a pre-release SDK version unless a pre-release version was specified via `global.json`
        ///  * `result` callback invoked to return resolved values.
        ///         The callback may be invoked more than once. Strings passed to the callback are valid only for the duration of the call.
        ///
        /// If resolution succeeds, result will be invoked with [`resolved_sdk_dir`](crate::hostfxr_resolve_sdk2_result_key_t::resolved_sdk_dir) key and the value will hold the path to the resolved SDK directory.
        /// If resolution does not succeed, result will be invoked with [`resolved_sdk_dir`](crate::hostfxr_resolve_sdk2_result_key_t::resolved_sdk_dir) key and the value will be [`ptr::null()`](core::ptr::null).
        ///
        /// If `global.json` is used, result will be invoked with [`global_json_path`](crate::hostfxr_resolve_sdk2_result_key_t::global_json_path) key and the value will hold the path to `global.json`.
        /// If there was no `global.json` found, or the contents of `global.json` did not impact resolution (e.g. no version specified), then result will not be invoked with [`global_json_path`](crate::hostfxr_resolve_sdk2_result_key_t::global_json_path) key.
        #[cfg(feature = "netcore2_1")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
        hostfxr_resolve_sdk2: unsafe extern "C" fn(
            exe_dir: *const char_t,
            working_dir: *const char_t,
            flags: hostfxr_resolve_sdk2_flags_t,
            result: hostfxr_resolve_sdk2_result_fn,
        ) -> i32,

        /// Get the list of all available SDKs ordered by ascending version.
        ///
        /// # Arguments
        ///  * `exe_dir` - path to the dotnet executable
        ///  * `result` - callback invoked to return the list of SDKs by their directory paths.
        ///             String array and its elements are valid only for the duration of the call.
        #[cfg(feature = "netcore2_1")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
        hostfxr_get_available_sdks: unsafe extern "C" fn(
            exe_dir: *const char_t,
            result: hostfxr_get_available_sdks_result_fn,
        ) -> i32,

        /// Get the native search directories of the runtime based upon the specified app.
        ///
        /// # Arguments
        ///  * `argc`,`argv` command-line arguments
        ///  * `buffer` buffer to populate with the native search directories (including a null terminator).
        ///  * `buffer_size` size of `buffer` in [`char_t`] units
        ///  * `required_buffer_size` if buffer is too small, this will be populated with the minimum required buffer size (including a null terminator). Otherwise, this will be set to 0.
        ///
        /// The native search directories will be a list of paths separated by [`PATH_LIST_SEPARATOR`], which is a semicolon (;) on Windows and a colon (:) otherwise.
        ///
        /// If `buffer_size` is less than the minimum required buffer size, this function will return [`HostApiBufferTooSmall`] and buffer will be unchanged.
        ///
        /// [`HostApiBufferTooSmall`]: coreclr_hosting_shared::StatusCode::HostApiBufferTooSmall
        /// [`PATH_LIST_SEPARATOR`]: crate::PATH_LIST_SEPARATOR
        #[cfg(feature = "netcore2_1")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore2_1")))]
        hostfxr_get_native_search_directories: unsafe extern "C" fn(
            argc: i32,
            argv: *const *const char_t,
            buffer: *mut char_t,
            buffer_size: i32,
            required_buffer_size: *mut i32,
        ) -> i32,

        /// Sets a callback which is to be used to write errors to.
        ///
        /// # Arguments
        ///  * `error_writer`
        ///     A callback function which will be invoked every time an error is to be reported.
        ///     Or [`null`](core::ptr::null()) to unregister previously registered callback and return to the default behavior.
        ///
        /// # Return value
        /// The previously registered callback (which is now unregistered), or [`null`](core::ptr::null()) if no previous callback
        /// was registered
        ///
        /// # Remarks
        /// The error writer is registered per-thread, so the registration is thread-local. On each thread
        /// only one callback can be registered. Subsequent registrations overwrite the previous ones.
        ///
        /// By default no callback is registered in which case the errors are written to stderr.
        ///
        /// Each call to the error writer is sort of like writing a single line (the EOL character is omitted).
        /// Multiple calls to the error writer may occure for one failure.
        ///
        /// If the hostfxr invokes functions in hostpolicy as part of its operation, the error writer
        /// will be propagated to hostpolicy for the duration of the call. This means that errors from
        /// both hostfxr and hostpolicy will be reporter through the same error writer.
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_set_error_writer:
            unsafe extern "C" fn(error_writer: Option<hostfxr_error_writer_fn>) -> Option<hostfxr_error_writer_fn>,

        /// Initializes the hosting components for a dotnet command line running an application
        ///
        /// # Arguments
        ///  * `argc`
        ///     Number of argv arguments
        ///  * `argv`
        ///     Command-line arguments for running an application (as if through the dotnet executable).
        ///  * `parameters`
        ///     Optional. Additional parameters for initialization
        ///  * `host_context_handle`
        ///     On success, this will be populated with an opaque value representing the initialized host context
        ///
        /// # Return value
        ///  * [`Success`]:
        ///     Hosting components were successfully initialized
        ///  * [`HostInvalidState`]:
        ///     Hosting components are already initialized
        ///
        /// # Remarks
        /// This function parses the specified command-line arguments to determine the application to run. It will
        /// then find the corresponding `.runtimeconfig.json` and `.deps.json` with which to resolve frameworks and
        /// dependencies and prepare everything needed to load the runtime.
        ///
        /// This function only supports arguments for running an application. It does not support SDK commands.
        ///
        /// This function does not load the runtime.
        ///
        /// [`Success`]: coreclr_hosting_shared::StatusCode::Success
        /// [`HostInvalidState`]: coreclr_hosting_shared::StatusCode::HostInvalidState
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_initialize_for_dotnet_command_line: unsafe extern "C" fn(
            argc: i32,
            argv: *const *const char_t,
            parameters: *const hostfxr_initialize_parameters,
            /*out*/ host_context_handle: *mut hostfxr_handle,
        ) -> i32,

        /// Initializes the hosting components using a `.runtimeconfig.json` file
        ///
        /// # Arguments
        ///  * `runtime_config_path`
        ///     Path to the `.runtimeconfig.json` file
        ///  * `parameters`
        ///     Optional. Additional parameters for initialization
        ///  * `host_context_handle`
        ///     On success, this will be populated with an opaque value representing the initialized host context
        ///
        /// # Return value
        /// * [`Success`]:
        ///      Hosting components were successfully initialized
        /// * [`Success_HostAlreadyInitialized`]:
        ///      Config is compatible with already initialized hosting components
        /// * [`Success_DifferentRuntimeProperties`]:
        ///      Config has runtime properties that differ from already initialized hosting components
        /// * [`CoreHostIncompatibleConfig`]:
        ///      Config is incompatible with already initialized hosting components
        ///
        /// # Remarks
        /// This function will process the `.runtimeconfig.json` to resolve frameworks and prepare everything needed
        /// to load the runtime. It will only process the `.deps.json` from frameworks (not any app/component that
        /// may be next to the `.runtimeconfig.json`).
        ///
        /// This function does not load the runtime.
        ///
        /// If called when the runtime has already been loaded, this function will check if the specified runtime
        /// config is compatible with the existing runtime.
        ///
        /// Both [`Success_HostAlreadyInitialized`] and [`Success_DifferentRuntimeProperties`] codes are considered successful
        /// initializations. In the case of [`Success_DifferentRuntimeProperties`], it is left to the consumer to verify that
        /// the difference in properties is acceptable.
        ///
        /// [`Success`]: coreclr_hosting_shared::StatusCode::Success
        /// [`Success_HostAlreadyInitialized`]: coreclr_hosting_shared::StatusCode::Success_HostAlreadyInitialized
        /// [`Success_DifferentRuntimeProperties`]: coreclr_hosting_shared::StatusCode::Success_DifferentRuntimeProperties
        /// [`CoreHostIncompatibleConfig`]: coreclr_hosting_shared::StatusCode::CoreHostIncompatibleConfig
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_initialize_for_runtime_config: unsafe extern "C" fn(
            runtime_config_path: *const char_t,
            parameters: *const hostfxr_initialize_parameters,
            /*out*/ host_context_handle: *mut hostfxr_handle,
        ) -> i32,

        /// Gets the runtime property value for an initialized host context
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///  * `name`
        ///     Runtime property name
        ///  * `value`
        ///     Out parameter. Pointer to a buffer with the property value.
        ///
        /// # Return value
        /// The error code result.
        ///
        /// # Remarks
        /// The buffer pointed to by value is owned by the host context. The lifetime of the buffer is only
        /// guaranteed until any of the below occur:
        ///  * a 'run' method is called for the host context
        ///  * properties are changed via [`hostfxr_set_runtime_property_value`]
        ///  * the host context is closed via [`hostfxr_close`]
        ///
        /// If `host_context_handle` is [`null`](core::ptr::null()) and an active host context exists, this function will get the
        /// property value for the active host context.
        ///
        /// [`hostfxr_set_runtime_property_value`]: struct.HostfxrLib.html#method.hostfxr_set_runtime_property_value
        /// [`hostfxr_close`]: struct.HostfxrLib.html#method.hostfxr_close
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_get_runtime_property_value: unsafe extern "C" fn(
            host_context_handle: hostfxr_handle,
            name: *const char_t,
            /*out*/ value: *mut *const char_t,
        ) -> i32,

        /// Sets the value of a runtime property for an initialized host context
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///  * `name`
        ///     Runtime property name
        ///  * `value`
        ///     Value to set
        ///
        /// # Return value
        /// The error code result.
        ///
        /// # Remarks
        /// Setting properties is only supported for the first host context, before the runtime has been loaded.
        ///
        /// If the property already exists in the host context, it will be overwritten. If value is [`null`](core::ptr::null()), the
        /// property will be removed.
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_set_runtime_property_value: unsafe extern "C" fn(
            host_context_handle: hostfxr_handle,
            name: *const char_t,
            value: *const char_t,
        ) -> i32,

        /// Gets all the runtime properties for an initialized host context
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///  * `count`
        ///     \[in\] Size of the keys and values buffers
        ///     \[out\] Number of properties returned (size of keys/values buffers used). If the input value is too
        ///             small or keys/values is [`null`](core::ptr::null()), this is populated with the number of available properties
        ///  * `keys`
        ///     \[out\] Array of pointers to buffers with runtime property keys
        ///  * `values`
        ///     \[out\] Array of pointers to buffers with runtime property values
        ///
        /// # Return value
        /// The error code result.
        ///
        /// # Remarks
        /// The buffers pointed to by keys and values are owned by the host context. The lifetime of the buffers is only
        /// guaranteed until any of the below occur:
        ///  * a 'run' method is called for the host context
        ///  * properties are changed via [`hostfxr_set_runtime_property_value`]
        ///  * the host context is closed via [`hostfxr_close`]
        ///
        /// If host_context_handle is [`null`](core::ptr::null()) and an active host context exists, this function will get the
        /// properties for the active host context.
        ///
        /// [`hostfxr_set_runtime_property_value`]: struct.HostfxrLib.html#hostfxr_set_runtime_property_value
        /// [`hostfxr_close`]: struct.HostfxrLib.html#method.hostfxr_closee
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_get_runtime_properties: unsafe extern "C" fn(
            host_context_handle: hostfxr_handle,
            /*inout*/ count: *mut size_t,
            /*out*/ keys: *mut *const char_t,
            /*out*/ values: *mut *const char_t,
        ) -> i32,

        /// Load CoreCLR and run the application for an initialized host context
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///
        /// # Return value
        /// If the app was successfully run, the exit code of the application. Otherwise, the error code result.
        ///
        /// # Remarks
        /// The `host_context_handle` must have been initialized using [`hostfxr_initialize_for_dotnet_command_line`].
        ///
        /// This function will not return until the managed application exits.
        ///
        /// [`hostfxr_initialize_for_runtime_config`]: struct.HostfxrLib.html#method.hostfxr_initialize_for_runtime_config
        /// [`hostfxr_initialize_for_dotnet_command_line`]: struct.HostfxrLib.html#method.hostfxr_initialize_for_dotnet_command_line
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_run_app: unsafe extern "C" fn(host_context_handle: hostfxr_handle) -> i32,

        /// Gets a typed delegate from the currently loaded CoreCLR or from a newly created one.
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///  * `type`
        ///     Type of runtime delegate requested
        ///  * `delegate`
        ///     An out parameter that will be assigned the delegate.
        ///
        /// # Return value
        /// The error code result.
        ///
        /// # Remarks
        /// If the `host_context_handle` was initialized using [`hostfxr_initialize_for_runtime_config`],
        /// then all delegate types are supported.
        /// If the host_context_handle was initialized using [`hostfxr_initialize_for_dotnet_command_line`],
        /// then only the following delegate types are currently supported:
        ///  * [`hdt_load_assembly_and_get_function_pointer`]
        ///  * [`hdt_get_function_pointer`]
        ///
        /// [`hdt_load_assembly_and_get_function_pointer`]: hostfxr_delegate_type::hdt_load_assembly_and_get_function_pointer
        /// [`hdt_get_function_pointer`]: hostfxr_delegate_type::hdt_get_function_pointer
        /// [`hostfxr_initialize_for_runtime_config`]: struct.HostfxrLib.html#method.hostfxr_initialize_for_runtime_config
        /// [`hostfxr_initialize_for_dotnet_command_line`]: struct.HostfxrLib.html#method.hostfxr_initialize_for_dotnet_command_line
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_get_runtime_delegate: unsafe extern "C" fn(
            host_context_handle: hostfxr_handle,
            r#type: hostfxr_delegate_type,
            /*out*/ delegate: *mut *const (),
        ) -> i32,

        /// Closes an initialized host context.
        ///
        /// # Arguments
        ///  * `host_context_handle`
        ///     Handle to the initialized host context
        ///
        /// # Return value
        /// The error code result.
        #[cfg(feature = "netcore3_0")]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "netcore3_0")))]
        hostfxr_close: unsafe extern "C" fn(host_context_handle: hostfxr_handle) -> i32,

        /// Returns available SDKs and frameworks.
        ///
        /// Resolves the existing SDKs and frameworks from a dotnet root directory (if
        /// any), or the global default location. If multi-level lookup is enabled and
        /// the dotnet root location is different than the global location, the SDKs and
        /// frameworks will be enumerated from both locations.
        ///
        /// The SDKs are sorted in ascending order by version, multi-level lookup
        /// locations are put before private ones.
        ///
        /// The frameworks are sorted in ascending order by name followed by version,
        /// multi-level lookup locations are put before private ones.
        ///
        /// # Arguments
        ///  * `dotnet_root`
        ///      The path to a directory containing a dotnet executable.
        ///  *  `reserved`
        ///      Reserved for future parameters.
        ///  *  `result`
        ///      Callback invoke to return the list of SDKs and frameworks.
        ///      Structs and their elements are valid for the duration of the call.
        ///  * `result_context`
        ///      Additional context passed to the result callback.
        ///
        /// # Return value
        /// The error code result.
        #[cfg(all(feature = "net6_0", feature = "undocumented"))]
        #[cfg_attr(feature = "doc-cfg", doc(cfg(all(feature = "net6_0", feature = "undocumented"))))]
        hostfxr_get_dotnet_environment_info: unsafe extern "C" fn(
            dotnet_root: *const char_t,
            reserved: *mut c_void,
            result: hostfxr_get_dotnet_environment_info_result_fn,
            result_context: *mut c_void
        ) -> i32,
    }
}