Skip to main content

st_zrt_sys/
lib.rs

1//! st-zrt-sys — hand-written FFI to libonnxruntime, in the `zrt` namespace.
2//!
3//! NO bindgen: `OrtApi`'s function-pointer table is macro-defined (bindgen can't parse
4//! it and drags in legacy `Ort*` names). Instead, the `st-zrt-sys-codegen` tool
5//! preprocesses `onnxruntime_c_api.h` (`gcc -E -P`), parses the fully-expanded
6//! `struct OrtApi`, and emits [`mod generated`] — the exhaustive IDX_*/typed-alias/
7//! accessor table with zrt names. This file keeps only the hand-written core: opaque
8//! handles, the stable enums, `ApiBase`, the `Api` table primitive, the entry point,
9//! and `status_to_result`.
10//!
11//! The only C symbol linked by name is `OrtGetApiBase` (`#[link_name]`); everything
12//! else is reached through `Api` by positional index.
13#![allow(non_camel_case_types, non_snake_case, dead_code, clippy::all)]
14
15use std::ffi::c_void;
16use std::os::raw::c_char;
17#[cfg(feature = "custom-ops")]
18use std::os::raw::c_int;
19
20/// libonnxruntime API version we bind (1.27.0 → API version 27).
21pub const API_VERSION: u32 = 29;
22
23/// The exact libonnxruntime version this crate acquires and links by default.
24///
25/// Injected by `build.rs` from the same constant that drives the download/sha256 table, so
26/// the artifact, the pin, and this public constant cannot drift apart.
27pub const ORT_VERSION: &str = env!("ST_ZRT_ORT_VERSION");
28
29/// libonnxruntime release lines whose runtime these API-{API_VERSION} bindings support.
30///
31/// The default acquisition is [`ORT_VERSION`] (`1.29`). Only the `1.29` line is supported:
32/// the bindings request the API-29 table via `GetApi(29)`, which an older runtime cannot
33/// serve (the C API grows append-only, so older libraries expose fewer table entries), and
34/// newer lines are unvalidated. Bind a different 1.29.x runtime by pointing
35/// `ST_ZRT_ORT_PATH` at an extracted onnxruntime directory (see the build-script docs).
36/// The safe wrapper rejects every other line at `Environment` creation;
37/// [`runtime_version_supported`] is the predicate.
38pub const SUPPORTED_RUNTIME_LINES: &[&str] = &["1.29"];
39
40/// `GetVersionString()` of the loaded libonnxruntime, if the entry point is callable.
41///
42/// Returns the runtime's own version string (e.g. `"1.29.0"`), not the pinned
43/// [`ORT_VERSION`]: it reports what the dynamic loader actually resolved.
44#[inline]
45pub fn runtime_version_string() -> Option<String> {
46    let base = api_base();
47    if base.is_null() {
48        return None;
49    }
50    unsafe { (*base).version_string() }.map(|s| s.to_string_lossy().into_owned())
51}
52
53/// Whether a `GetVersionString()` result belongs to a [`SUPPORTED_RUNTIME_LINES`] line.
54///
55/// Matches on `major.minor` only, so any patch (and pre-release suffix) of a supported
56/// line passes and anything else — older lines, newer lines, a different major — fails.
57pub fn runtime_version_supported(version: &str) -> bool {
58    let mut fields = version.split('.');
59    match (fields.next(), fields.next()) {
60        (Some(major), Some(minor)) => SUPPORTED_RUNTIME_LINES
61            .iter()
62            .any(|line| line.split('.').take(2).eq([major, minor])),
63        _ => false,
64    }
65}
66
67// ─── opaque-handle macro (the generated table invokes this) ──────────────────
68macro_rules! opaque_handle {
69    ($name:ident) => {
70        #[repr(C)]
71        pub struct $name(crate::private::Opaque);
72    };
73}
74mod private {
75    /// Incomplete-opaque marker. We only ever hold `*mut Handle` values handed to us
76    /// by ORT; the interior is never constructed or read on our side.
77    #[repr(C)]
78    pub struct Opaque(*const u8);
79}
80
81// ─── enums (ONNX / ORT values, stable) ───────────────────────────────────────
82/// ONNXTensorElementDataType.
83#[repr(i32)]
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum ElementType {
86    Undefined = 0,
87    Float = 1,
88    Uint8 = 2,
89    Int8 = 3,
90    Uint16 = 4,
91    Int16 = 5,
92    Int32 = 6,
93    Int64 = 7,
94    String = 8,
95    Bool = 9,
96    Float16 = 10,
97    Double = 11,
98    Uint32 = 12,
99    Uint64 = 13,
100    Complex64 = 14,
101    Complex128 = 15,
102    Bfloat16 = 16,
103    Float8E4M3FN = 17,
104    Float8E4M3FNUZ = 18,
105    Float8E5M2 = 19,
106    Float8E5M2FNUZ = 20,
107    Uint4 = 21,
108    Int4 = 22,
109    Float4E2M1 = 23,
110    Uint2 = 24,
111    Int2 = 25,
112    Float8E8M0 = 26,
113}
114
115/// OrtLoggingLevel (a.k.a. LogLevel).
116#[repr(i32)]
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum LoggingLevel {
119    Verbose = 0,
120    Info = 1,
121    Warning = 2,
122    Error = 3,
123    Fatal = 4,
124}
125pub type LogLevel = LoggingLevel;
126
127/// GraphOptimizationLevel.
128#[repr(i32)]
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum GraphOptimizationLevel {
131    DisableAll = 0,
132    Basic = 1,
133    Extended = 2,
134    Layout = 3,
135    All = 99,
136}
137
138/// OrtAllocatorType.
139#[repr(i32)]
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum AllocatorType {
142    Invalid = -1,
143    Device = 0,
144    Arena = 1,
145    ReadOnly = 2,
146}
147
148/// OrtMemType.
149#[repr(i32)]
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum MemType {
152    CpuInput = -2,
153    CpuOutput = -1,
154    Default = 0,
155}
156
157/// OrtProfilingEventCategory (onnxruntime_ep_c_api.h). The granularity of an EP profiling event,
158/// passed to `CreateProfilingEvent` and read back via `ProfilingEvent_GetCategory`. A plain int enum
159/// — *not* an opaque handle — so it is modelled here, like [`MemType`].
160#[repr(i32)]
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum ProfilingEventCategory {
163    Session = 0,
164    Node = 1,
165    Kernel = 2,
166    Api = 3,
167}
168
169const _: () = assert!(
170    std::mem::size_of::<ProfilingEventCategory>() == std::mem::size_of::<core::ffi::c_int>()
171);
172const _: () = assert!(
173    std::mem::align_of::<ProfilingEventCategory>() == std::mem::align_of::<core::ffi::c_int>()
174);
175const _: () = assert!(ProfilingEventCategory::Session as i32 == 0);
176const _: () = assert!(ProfilingEventCategory::Node as i32 == 1);
177const _: () = assert!(ProfilingEventCategory::Kernel as i32 == 2);
178const _: () = assert!(ProfilingEventCategory::Api as i32 == 3);
179
180/// ONNXType (the top-level value kind).
181#[repr(i32)]
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum OnnxType {
184    Unknown = 0,
185    Tensor = 1,
186    Sequence = 2,
187    Map = 3,
188    Optional = 4,
189    SparseTensor = 5,
190    Opaque = 6,
191}
192
193/// OrtSparseFormat.
194#[repr(i32)]
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum SparseFormat {
197    Undefined = 0,
198    Coo = 0x1,
199    Csrc = 0x2,
200    BlockSparse = 0x4,
201}
202
203/// OrtSparseIndicesFormat.
204#[repr(i32)]
205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum SparseIndicesFormat {
207    Coo = 0,
208    CsrInner = 1,
209    CsrOuter = 2,
210    BlockSparse = 3,
211}
212
213/// OrtEpDataLayout (onnxruntime_ep_c_api.h). An EP's preferred tensor data layout. `Default` is an
214/// alias for `Nchw` (= 0), so only the two concrete variants are modelled.
215#[repr(i32)]
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum EpDataLayout {
218    Nchw = 0,
219    Nhwc = 1,
220}
221
222/// OrtGraphCaptureNodeAssignmentPolicy (onnxruntime_ep_c_api.h). How strictly ORT validates node
223/// assignment when an EP enables CUDA-graph-style capture.
224#[repr(i32)]
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum GraphCaptureNodeAssignmentPolicy {
227    AllNodesOnEp = 0,
228    AllowCpuForShapes = 1,
229}
230
231/// ExecutionMode.
232#[repr(i32)]
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum ExecutionMode {
235    Sequential = 0,
236    Parallel = 1,
237}
238
239/// OrtExecutionProviderDevicePolicy.
240#[repr(i32)]
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub enum ExecutionProviderDevicePolicy {
243    Default = 0,
244    PreferCpu = 1,
245    PreferNpu = 2,
246    PreferGpu = 3,
247    MaxPerformance = 4,
248    MaxEfficiency = 5,
249    MinOverallPower = 6,
250}
251
252/// OrtErrorCode — the status code `GetErrorCode` returns and `CreateStatus` accepts
253/// (`onnxruntime_c_api.h:257-273`). `#[repr(i32)]` makes it ABI-compatible with the
254/// `c_int`-typed generated status API (`CreateStatusFn` / `GetErrorCodeFn` — both map the
255/// C `OrtErrorCode` to `c_int`).
256#[repr(i32)]
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum OrtErrorCode {
259    /// `ORT_OK` — success.
260    Ok = 0,
261    /// `ORT_FAIL` — generic failure; also the code custom-op kernels surface on error.
262    Fail = 1,
263    /// `ORT_INVALID_ARGUMENT`.
264    InvalidArgument = 2,
265    /// `ORT_NO_SUCHFILE`.
266    NoSuchFile = 3,
267    /// `ORT_NO_MODEL`.
268    NoModel = 4,
269    /// `ORT_ENGINE_ERROR`.
270    EngineError = 5,
271    /// `ORT_RUNTIME_EXCEPTION`.
272    RuntimeException = 6,
273    /// `ORT_INVALID_PROTOBUF`.
274    InvalidProtobuf = 7,
275    /// `ORT_MODEL_LOADED`.
276    ModelLoaded = 8,
277    /// `ORT_NOT_IMPLEMENTED`.
278    NotImplemented = 9,
279    /// `ORT_INVALID_GRAPH`.
280    InvalidGraph = 10,
281    /// `ORT_EP_FAIL`.
282    EpFail = 11,
283    /// `ORT_MODEL_LOAD_CANCELED`.
284    ModelLoadCanceled = 12,
285    /// `ORT_MODEL_REQUIRES_COMPILATION`.
286    ModelRequiresCompilation = 13,
287    /// `ORT_NOT_FOUND`.
288    NotFound = 14,
289}
290
291impl OrtErrorCode {
292    /// Map a raw `c_int` error code to the enum, or `None` if it is outside the known range
293    /// (a future ORT version could add codes; st-zrt-local errors use negative codes).
294    pub fn from_c_int(code: core::ffi::c_int) -> Option<Self> {
295        Some(match code {
296            0 => Self::Ok,
297            1 => Self::Fail,
298            2 => Self::InvalidArgument,
299            3 => Self::NoSuchFile,
300            4 => Self::NoModel,
301            5 => Self::EngineError,
302            6 => Self::RuntimeException,
303            7 => Self::InvalidProtobuf,
304            8 => Self::ModelLoaded,
305            9 => Self::NotImplemented,
306            10 => Self::InvalidGraph,
307            11 => Self::EpFail,
308            12 => Self::ModelLoadCanceled,
309            13 => Self::ModelRequiresCompilation,
310            14 => Self::NotFound,
311            _ => return None,
312        })
313    }
314}
315
316/// OrtOpAttrType — the value kind of a custom-op attribute (CreateOpAttr / OpAttr_GetType).
317#[repr(i32)]
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
319pub enum OpAttrType {
320    Undefined = 0,
321    Int = 1,
322    Ints = 2,
323    Float = 3,
324    Floats = 4,
325    String = 5,
326    Strings = 6,
327    Graph = 7,
328    Tensor = 8,
329}
330
331// ─── custom-op authoring: the OrtCustomOp vtable (feature `custom-ops`) ───────
332//
333// `OrtCustomOp` is the struct a custom-op author fills in: the op's schema (name,
334// input/output element types + characteristics, opset range) plus the kernel callbacks ORT
335// invokes (Create/Compute/Destroy). It is passed to ORT by pointer (via
336// `CustomOpDomain_Add`); its storage must outlive every session using it (a `pub static`
337// built by the `custom_op!` macro satisfies this).
338//
339// The field *parameter types* are erased to `*const c_void` / `*mut c_void` for the ORT
340// handles (`op`, `api`, `info`, `ctx`, the shape-infer context) — this is layout-neutral
341// (every fn-pointer slot is one word regardless of its signature, so only field COUNT/ORDER
342// must match the C `struct OrtCustomOp` in onnxruntime_c_api.h), and the `custom_op!`
343// trampolines cast to the real handle types at call time. `version` must equal
344// `API_VERSION` (ORT reads it to size the table).
345#[cfg(feature = "custom-ops")]
346#[repr(C)]
347pub struct OrtCustomOp {
348    pub version: u32,
349    pub create_kernel: Option<
350        unsafe extern "C" fn(
351            op: *const c_void,
352            api: *const c_void,
353            info: *const c_void,
354        ) -> *mut c_void,
355    >,
356    pub get_name: Option<unsafe extern "C" fn(op: *const c_void) -> *const c_char>,
357    pub get_execution_provider_type:
358        Option<unsafe extern "C" fn(op: *const c_void) -> *const c_char>,
359    pub get_input_type: Option<unsafe extern "C" fn(op: *const c_void, index: usize) -> i32>,
360    pub get_input_type_count: Option<unsafe extern "C" fn(op: *const c_void) -> usize>,
361    pub get_output_type: Option<unsafe extern "C" fn(op: *const c_void, index: usize) -> i32>,
362    pub get_output_type_count: Option<unsafe extern "C" fn(op: *const c_void) -> usize>,
363    pub kernel_compute: Option<unsafe extern "C" fn(kernel: *mut c_void, ctx: *mut c_void)>,
364    pub kernel_destroy: Option<unsafe extern "C" fn(kernel: *mut c_void)>,
365    pub get_input_characteristic:
366        Option<unsafe extern "C" fn(op: *const c_void, index: usize) -> i32>,
367    pub get_output_characteristic:
368        Option<unsafe extern "C" fn(op: *const c_void, index: usize) -> i32>,
369    pub get_input_memory_type: Option<unsafe extern "C" fn(op: *const c_void, index: usize) -> i32>,
370    pub get_variadic_input_min_arity: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
371    pub get_variadic_input_homogeneity: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
372    pub get_variadic_output_min_arity: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
373    pub get_variadic_output_homogeneity: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
374    pub create_kernel_v2: Option<
375        unsafe extern "C" fn(
376            op: *const c_void,
377            api: *const c_void,
378            info: *const c_void,
379            kernel: *mut *mut c_void,
380        ) -> generated::StatusPtr,
381    >,
382    pub kernel_compute_v2:
383        Option<unsafe extern "C" fn(kernel: *mut c_void, ctx: *mut c_void) -> generated::StatusPtr>,
384    pub infer_output_shape_fn:
385        Option<unsafe extern "C" fn(op: *const c_void, sctx: *mut c_void) -> generated::StatusPtr>,
386    pub get_start_version: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
387    pub get_end_version: Option<unsafe extern "C" fn(op: *const c_void) -> c_int>,
388    pub get_may_inplace: Option<
389        unsafe extern "C" fn(input_index: *mut *mut c_int, output_index: *mut *mut c_int) -> usize,
390    >,
391    pub release_may_inplace:
392        Option<unsafe extern "C" fn(input_index: *mut c_int, output_index: *mut c_int)>,
393    pub get_alias_map: Option<
394        unsafe extern "C" fn(input_index: *mut *mut c_int, output_index: *mut *mut c_int) -> usize,
395    >,
396    pub release_alias_map:
397        Option<unsafe extern "C" fn(input_index: *mut c_int, output_index: *mut c_int)>,
398}
399
400/// OrtCustomOpInputOutputCharacteristic — whether an input/output is required, optional, or
401/// variadic (onnxruntime_c_api.h:7456). `#[repr(i32)]` matches the C `enum`.
402#[cfg(feature = "custom-ops")]
403#[repr(i32)]
404#[derive(Debug, Clone, Copy, PartialEq, Eq)]
405pub enum CustomOpInputOutputCharacteristic {
406    Required = 0,
407    Optional = 1,
408    Variadic = 2,
409}
410
411// Compile-time check: the `#[repr(C)]` table is exactly 208 bytes on 64-bit
412// (1×u32 + 4 pad + 25 fn-ptr slots). Catches a wrong field *count*; field *order* is pinned
413// by the named-field construction and checked at runtime in st-zrt-sys's test suite.
414#[cfg(feature = "custom-ops")]
415const _: () = assert!(std::mem::size_of::<OrtCustomOp>() == 208);
416
417/// OrtLoggingFunction — the custom-logger callback (`CreateEnvWithCustomLogger`).
418pub type LoggingFunction = Option<
419    unsafe extern "C" fn(
420        param: *mut c_void,
421        severity: LoggingLevel,
422        category: *const c_char,
423        logid: *const c_char,
424        status_messages: *const *const c_char,
425        num_status_messages: usize,
426    ),
427>;
428
429// ─── ApiBase ─────────────────────────────────────────────────────────────────
430/// `OrtApiBase`. We only use `GetApi` (offset 0) and `GetVersionString` (offset 1).
431#[repr(C)]
432pub struct ApiBase {
433    pub get_api: Option<unsafe extern "C" fn(version: u32) -> *const Api>,
434    pub get_version_string: Option<unsafe extern "C" fn() -> *const c_char>,
435}
436
437impl ApiBase {
438    #[inline]
439    pub unsafe fn version_string(&self) -> Option<&'static std::ffi::CStr> {
440        unsafe {
441            let f = self.get_version_string?;
442            Some(std::ffi::CStr::from_ptr(f()))
443        }
444    }
445}
446
447// ─── Api: the function-pointer table primitive ───────────────────────────────
448/// `OrtApi` — a table of function pointers, indexed positionally. The struct is
449/// effectively `[*const c_void; N]` (all slots pointer-sized, no padding). The
450/// generated table (in [`mod generated`]) adds the typed accessors.
451#[repr(C)]
452pub struct Api([u8; 0]);
453
454impl Api {
455    /// Read the raw function pointer at positional index `idx`.
456    #[inline]
457    pub unsafe fn fn_ptr(&self, idx: usize) -> *const c_void {
458        unsafe {
459            (self as *const Self as *const *const c_void)
460                .add(idx)
461                .read()
462        }
463    }
464
465    /// Typed accessor used by every generated wrapper: null-check the slot, then
466    /// reinterpret the data pointer as the fn-pointer type `T`.
467    #[inline]
468    unsafe fn f<T: Copy>(&self, idx: usize) -> T {
469        unsafe {
470            let p = self.fn_ptr(idx);
471            assert!(
472                !p.is_null(),
473                "st-zrt-sys: Api[{idx}] is null — header/version mismatch"
474            );
475            std::mem::transmute_copy(&p)
476        }
477    }
478}
479
480/// GENERATED: the exhaustive `OrtApi` table — IDX_* indices, typed fn aliases, Api
481/// accessors, and the opaque handle types. zrt names; no `Ort*`; no bindgen.
482/// Regenerate via `cargo run -p st-zrt-sys-codegen -- <header> <this file>`.
483pub mod generated;
484
485// EP-author implementor vtable structs (OrtEp / OrtEpFactory / OrtNodeComputeInfo), produced by an
486// EP author and handed to ORT. Gated to `model-editor` alongside the safe EpAuthor surface.
487#[cfg(feature = "model-editor")]
488pub mod ep_vtables;
489
490// ─── entry point (the one C symbol we link by name) ──────────────────────────
491unsafe extern "C" {
492    #[link_name = "OrtGetApiBase"]
493    fn get_api_base_ffi() -> *const ApiBase;
494}
495
496/// The global `OrtApiBase`.
497#[inline]
498pub fn api_base() -> *const ApiBase {
499    unsafe { get_api_base_ffi() }
500}
501
502/// The `Api` function-pointer table for [`API_VERSION`].
503///
504/// # Panics
505/// Panics if the engine can't be loaded or the API version is unavailable.
506#[inline]
507pub fn api() -> *const Api {
508    unsafe {
509        let base = get_api_base_ffi();
510        assert!(
511            !base.is_null(),
512            "st-zrt-sys: OrtGetApiBase returned null — libonnxruntime not loaded"
513        );
514        let get_api = (*base).get_api.expect("st-zrt-sys: GetApi missing");
515        let api = get_api(API_VERSION);
516        assert!(
517            !api.is_null(),
518            "st-zrt-sys: GetApi({API_VERSION}) returned null — version mismatch with libonnxruntime"
519        );
520        api
521    }
522}
523
524/// Turn a raw `OrtStatus*` into `Result`: `Ok(())` if null, else code+message.
525/// On the error path the status is consumed (released).
526#[inline]
527pub unsafe fn status_to_result(
528    api: &Api, status: generated::StatusPtr,
529) -> Result<(), (i32, std::ffi::CString)> {
530    unsafe {
531        if status.is_null() {
532            return Ok(());
533        }
534        let code = api.get_error_code()(status as *const generated::StatusHandle);
535        let msg_ptr = api.get_error_message()(status as *const generated::StatusHandle);
536        let msg = if msg_ptr.is_null() {
537            std::ffi::CString::new("(null error message)").unwrap()
538        } else {
539            std::ffi::CStr::from_ptr(msg_ptr).to_owned()
540        };
541        api.release_status()(status);
542        Err((code, msg))
543    }
544}
545
546// Re-export the generated table at the crate root so callers use `st_zrt_sys::IDX_RUN`
547// / `st_zrt_sys::Api` uniformly regardless of whether a symbol is hand-written or
548// generated.
549pub use generated::*;
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554
555    #[test]
556    fn api_table_loads() {
557        let base = api_base();
558        assert!(!base.is_null(), "api_base() null");
559        let api = api();
560        assert!(!api.is_null(), "api() null — GetApi({API_VERSION}) failed");
561        if let Some(s) = runtime_version_string() {
562            eprintln!("onnxruntime: {s}");
563            assert!(
564                runtime_version_supported(&s),
565                "loaded libonnxruntime {s:?} is not a supported line                  {SUPPORTED_RUNTIME_LINES:?} for st-zrt-sys {ORT_VERSION}"
566            );
567        }
568    }
569
570    #[test]
571    fn runtime_version_matching() {
572        for accepted in ["1.29.0", "1.29.999", "1.29.1", "1.29.0-rc2"] {
573            assert!(
574                runtime_version_supported(accepted),
575                "should accept {accepted:?}"
576            );
577        }
578        for rejected in [
579            "1.26.0",
580            "1.27.1",
581            "1.28.1",
582            "1.99.0",
583            "2.0.0",
584            "1.2",
585            "1",
586            "",
587            "onnxruntime",
588        ] {
589            assert!(
590                !runtime_version_supported(rejected),
591                "should reject {rejected:?}"
592            );
593        }
594    }
595
596    /// Functional index proof: call CreateSessionOptions(idx 10) + Release(idx 100)
597    /// through the GENERATED table. Crashes/errors if any index/signature is wrong.
598    #[test]
599    fn generated_indices_functionally_validated() {
600        unsafe {
601            let api_ref = &*api();
602            let mut opts: *mut SessionOptionsHandle = std::ptr::null_mut();
603            let st = api_ref.create_session_options()(&mut opts);
604            assert!(st.is_null(), "CreateSessionOptions failed");
605            assert!(!opts.is_null(), "CreateSessionOptions gave null handle");
606            api_ref.release_session_options()(opts);
607            eprintln!(
608                "generated_indices_functionally_validated: CreateSessionOptions(10) + Release(100) OK"
609            );
610        }
611    }
612
613    /// Exhaustive table-shape proof for ORT 1.27: every generated `OrtApi` field index
614    /// is present in the live `GetApi(27)` table. This catches header/table drift before
615    /// any safe wrapper reaches a null slot.
616    #[test]
617    fn generated_api_table_slots_are_non_null() {
618        unsafe {
619            let api_ref = &*api();
620            for idx in 0..=generated::IDX_SESSION_RELEASE_CAPTURED_GRAPH {
621                assert!(!api_ref.fn_ptr(idx).is_null(), "OrtApi slot {idx} is null");
622            }
623        }
624    }
625
626    /// Proves the `OrtErrorCode` enum's integer values match ORT's encoding: build a status
627    /// with `CreateStatus(<code>)`, read it back with `GetErrorCode`, and assert the round
628    /// trip for several variants. Exercises IDX_CREATE_STATUS (0) + IDX_GET_ERROR_CODE (1).
629    #[test]
630    fn ort_error_code_round_trips() {
631        unsafe {
632            let api_ref = &*api();
633            let msg = b"zrt probe\0";
634            for code in [
635                OrtErrorCode::InvalidArgument,
636                OrtErrorCode::Fail,
637                OrtErrorCode::NotFound,
638            ] {
639                let status = api_ref.create_status()(code as core::ffi::c_int, msg.as_ptr().cast());
640                assert!(!status.is_null(), "CreateStatus gave a null status");
641                let got = api_ref.get_error_code()(status as *const StatusHandle);
642                assert_eq!(got, code as core::ffi::c_int, "GetErrorCode round trip");
643                assert_eq!(
644                    OrtErrorCode::from_c_int(got),
645                    Some(code),
646                    "from_c_int maps back"
647                );
648                api_ref.release_status()(status);
649            }
650            eprintln!(
651                "ort_error_code_round_trips: enum values match ORT (InvalidArgument/Fail/NotFound)"
652            );
653        }
654    }
655
656    /// The four sub-API gateway getters (model-editor feature) must return non-null at
657    /// API version 27 — proves the gateway indices are correct and that ORT populates the
658    /// OrtModelEditorApi / OrtCompileApi / OrtEpApi / OrtInteropApi function tables. A
659    /// wrong index crashes; a null means ORT didn't populate that sub-API.
660    #[cfg(feature = "model-editor")]
661    #[test]
662    fn sub_api_gateways_non_null() {
663        unsafe {
664            let api_ref = &*api();
665            assert!(
666                !api_ref.get_model_editor_api()().is_null(),
667                "GetModelEditorApi null"
668            );
669            assert!(!api_ref.get_compile_api()().is_null(), "GetCompileApi null");
670            assert!(!api_ref.get_ep_api()().is_null(), "GetEpApi null");
671            assert!(!api_ref.get_interop_api()().is_null(), "GetInteropApi null");
672            eprintln!("sub-API gateways all non-null: model_editor/compile/ep/interop");
673        }
674    }
675
676    /// Pins the field *order* of `OrtCustomOp` (the size const-assert only catches a wrong
677    /// *count*; two transposed fn-ptr fields have the same size). `addr_of!` computes field
678    /// addresses without reading through the dangling pointer, so this is sound.
679    #[cfg(feature = "custom-ops")]
680    #[test]
681    fn ortcustomop_field_offsets() {
682        use core::ptr::addr_of;
683        let p = core::ptr::NonNull::<OrtCustomOp>::dangling().as_ptr();
684        let base = p as *const u8 as usize;
685        unsafe {
686            assert_eq!(addr_of!((*p).version) as *const u8 as usize - base, 0);
687            assert_eq!(addr_of!((*p).get_name) as *const u8 as usize - base, 16);
688            assert_eq!(
689                addr_of!((*p).create_kernel_v2) as *const u8 as usize - base,
690                136
691            );
692            assert_eq!(
693                addr_of!((*p).release_alias_map) as *const u8 as usize - base,
694                200
695            );
696        }
697        eprintln!(
698            "OrtCustomOp field order pinned: version@0, get_name@16, create_kernel_v2@136, release_alias_map@200"
699        );
700    }
701}