C/C++ API Overview
ONNX Runtime provides both C and C++ APIs for high-performance inference and training of deep learning models.API Design
C API
The C API (onnxruntime_c_api.h) is the foundation of ONNX Runtime:
- Version: Current API version is
ORT_API_VERSION 25 - Error Handling: Functions return
OrtStatus*(nullptr indicates success) - Memory Management: Manual memory management with explicit
Release*functions - Thread Safety: Most objects are not thread-safe unless explicitly documented
C++ API
The C++ API (onnxruntime_cxx_api.h) is a header-only wrapper around the C API:
- Exception Safety: Converts C error codes to C++ exceptions
- RAII: Automatic resource management through destructors
- Type Safety: Strong typing with C++ classes
- Move Semantics: Owning objects support move-only semantics
Core Concepts
Entry Point
Key Object Types
| C Type | C++ Type | Description |
|---|---|---|
OrtEnv | Ort::Env | Global environment, holds logging state |
OrtSessionOptions | Ort::SessionOptions | Configuration for session creation |
OrtSession | Ort::Session | Inference session containing a loaded model |
OrtValue | Ort::Value | Container for tensors and other ONNX types |
OrtMemoryInfo | Ort::MemoryInfo | Descriptor for memory location |
OrtAllocator | Ort::Allocator | Memory allocator interface |
Basic Workflow
1. Initialize Environment
2. Create Session Options
3. Load Model and Create Session
4. Prepare Input/Output
5. Run Inference
6. Cleanup
Error Handling
C API
All C API functions that can fail returnOrtStatus*:
NULLindicates success- Non-NULL indicates an error
C++ API
Errors are thrown asOrt::Exception:
Platform Considerations
Path Handling
- Windows: Use
wchar_t*for file paths (ORTCHAR_Tiswchar_t) - Linux/macOS: Use
char*for file paths (ORTCHAR_Tischar)
ORT_TSTR macro for portable string literals:
Thread Safety
OrtEnv: Thread-safeOrtSession: Can be used by multiple threads concurrently for inferenceOrtSessionOptions: Not thread-safe (use during session creation only)OrtValue: Not thread-safe
Data Types
Tensor Element Types
Next Steps
OrtApi Structure
Complete reference for all C API functions
Session Management
Loading models and running inference
Tensor Operations
Creating and manipulating tensors
Execution Providers
GPU acceleration and specialized hardware