labview_interop/sync.rs
1//! The sync module provides access to the
2//! functions which allow for synchronising
3//! back to labview.
4//!
5
6use std::ffi::c_void;
7use std::marker::PhantomData;
8
9use crate::errors::Result;
10use crate::labview::sync_api;
11use crate::memory::MagicCookie;
12
13type LVUserEventRef = MagicCookie;
14
15/// Representation of a LabVIEW user event reference with type data.
16///
17/// Where the reference is passed into Rust you can use this typed form
18/// to then allow proper type completions of the values.
19///
20/// From LabVIEW you can set the terminal to be `adapt to type` and `handles by value`
21///
22/// # Example
23/// ```
24/// # use labview_interop::sync::LVUserEvent;
25/// # use labview_interop::types::LVStatusCode;
26///#[no_mangle]
27///pub extern "C" fn generate_event_3(lv_user_event: *mut LVUserEvent<i32>) -> LVStatusCode {
28/// let event = unsafe { *lv_user_event };
29/// let result = event.post(&mut 3);
30/// match result {
31/// Ok(_) => LVStatusCode::SUCCESS,
32/// Err(err) => err.into(),
33/// }
34///}
35/// ```
36#[derive(Copy, Clone)]
37#[repr(transparent)]
38pub struct LVUserEvent<T> {
39 reference: LVUserEventRef,
40 _marker: PhantomData<T>,
41}
42
43impl<T> LVUserEvent<T> {
44 /// Generate the user event with the provided data.
45 ///
46 /// Right now the data needs to be a mutable reference as the
47 /// LabVIEW API does not specify whether it will not be modified.
48 pub fn post(&self, data: &mut T) -> Result<()> {
49 let mg_err = unsafe {
50 sync_api()?.post_lv_user_event(self.reference, data as *mut T as *mut c_void)
51 };
52 mg_err.to_specific_result(())
53 }
54}
55
56/// A LabVIEW occurence which can be used to provide synchronisation
57/// between execution of Rust and LabVIEW code.
58///
59/// From LabVIEW you can set the terminal to be `adapt to type` and `handles by value`
60///
61/// # Example
62/// ```
63/// # use labview_interop::sync::Occurence;
64/// # use labview_interop::types::LVStatusCode;
65/// #[no_mangle]
66///pub extern "C" fn generate_occurence(occurence: *mut Occurence) -> LVStatusCode {
67/// let result = unsafe { (*occurence).set() };
68/// match result {
69/// Ok(_) => LVStatusCode::SUCCESS,
70/// Err(err) => err.into(),
71/// }
72///}
73/// ```
74#[derive(Clone, Copy)]
75#[repr(transparent)]
76pub struct Occurence(MagicCookie);
77
78impl Occurence {
79 /// "set" generates the occurence event which can be detected by LabVIEW.
80 pub fn set(&self) -> Result<()> {
81 let mg_err = unsafe { sync_api()?.occur(self.0) };
82 mg_err.to_specific_result(())
83 }
84}