Skip to main content

onboardapi_sys/
lib.rs

1//! Raw FFI to the onboardapi C++ SDK.
2//!
3//! The C++ API (virtual callback interfaces, `std::string`/`std::vector` structs,
4//! templated factories) is not callable from Rust directly. A generated C++ shim
5//! (`shim/`) exposes every interface module as an [`obapi_vtable`] and moves all
6//! data across the boundary in one small binary format (see `shim/obapi_wire.hpp`).
7//!
8//! Use the safe `onboardapi` crate instead of this one.
9
10#![allow(non_camel_case_types)]
11
12use std::ffi::{c_char, c_void};
13
14#[rustfmt::skip]
15mod generated;
16pub use generated::*;
17
18pub const OBAPI_OK: i32 = 0;
19pub const OBAPI_ERR_EXCEPTION: i32 = -1;
20pub const OBAPI_ERR_UNKNOWN: i32 = -2;
21pub const OBAPI_ERR_WIRE: i32 = -3;
22pub const OBAPI_ERR_INVALID: i32 = -4;
23
24/// Called from onboardapi threads for every incoming operation.
25pub type obapi_dispatch_fn =
26    unsafe extern "C" fn(ctx: *mut c_void, op: u32, data: *const u8, len: usize);
27
28/// Mirror of `obapi_vtable` in `shim/obapi.h`.
29#[repr(C)]
30#[derive(Debug)]
31pub struct obapi_vtable {
32    pub module: *const c_char,
33    pub role: *const c_char,
34    pub create: unsafe extern "C" fn(
35        domain: i32,
36        name: *const c_char,
37        name_len: usize,
38        ctx: *mut c_void,
39        dispatch: Option<obapi_dispatch_fn>,
40        out: *mut *mut c_void,
41    ) -> i32,
42    pub send:
43        unsafe extern "C" fn(handle: *mut c_void, op: u32, data: *const u8, len: usize) -> i32,
44    pub destroy: unsafe extern "C" fn(handle: *mut c_void),
45    pub is_valid: unsafe extern "C" fn(handle: *mut c_void) -> bool,
46    pub wait_until_connected: Option<unsafe extern "C" fn(handle: *mut c_void) -> i32>,
47    pub set_name: Option<
48        unsafe extern "C" fn(handle: *mut c_void, name: *const c_char, name_len: usize) -> i32,
49    >,
50}
51
52// SAFETY: the vtables are immutable statics with 'static string pointers.
53unsafe impl Sync for obapi_vtable {}
54
55unsafe extern "C" {
56    /// Copies the calling thread's last error into `buf` (truncated) and returns its full length.
57    pub fn obapi_last_error(buf: *mut c_char, cap: usize) -> usize;
58}
59
60/// The last error message of the calling thread.
61pub fn last_error() -> String {
62    let mut buf = vec![0u8; 512];
63    // SAFETY: buf is valid for buf.len() bytes.
64    let n = unsafe { obapi_last_error(buf.as_mut_ptr().cast(), buf.len()) };
65    if n > buf.len() {
66        buf.resize(n, 0);
67        // SAFETY: as above, with the larger buffer.
68        unsafe { obapi_last_error(buf.as_mut_ptr().cast(), buf.len()) };
69    }
70    buf.truncate(n);
71    String::from_utf8_lossy(&buf).into_owned()
72}