diff --git a/.gitignore b/.gitignore
index 0df76f45..5b7a4172 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,6 +20,8 @@ Examples/**/build
Examples/**/build-*
Examples/**/bin
Examples/**/obj
+Examples/**/target
+Cargo.lock
# Visual Studio Code
debug
diff --git a/Build/Dockerfile b/Build/Dockerfile
index b2868d0b..0707714e 100644
--- a/Build/Dockerfile
+++ b/Build/Dockerfile
@@ -29,13 +29,18 @@ RUN dnf -y module enable python39 && \
# RUN dnf -y install libicu libicu-devel
# Free Pascal 3.0.4
-RUN (cd /opt && curl -O -L 'http://downloads.sourceforge.net/project/freepascal/Linux/3.0.4/fpc-3.0.4-1.x86_64.rpm' \
+RUN (cd /opt && curl -f -O -L --retry 5 --retry-delay 5 -C - 'https://downloads.freepascal.org/fpc/dist/3.0.4/x86_64-linux/fpc-3.0.4-1.x86_64.rpm' \
&& rpm -i fpc-3.0.4-1.x86_64.rpm)
# Go
RUN (cd /opt && curl -O -L https://golang.org/dl/go1.17.2.linux-amd64.tar.gz && tar zxvf go1.17.2.linux-amd64.tar.gz)
ENV PATH="${PATH}:/opt/go/bin"
+# Rust
+ENV RUSTUP_HOME=/opt/rustup CARGO_HOME=/opt/cargo
+RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --no-modify-path
+ENV PATH="${PATH}:/opt/cargo/bin"
+
# Java & Mono
RUN dnf -y install java-11-openjdk-devel
RUN rpm --import https://download.mono-project.com/repo/xamarin.gpg \
diff --git a/Build/build.bat b/Build/build.bat
index 91fce019..a102db3a 100644
--- a/Build/build.bat
+++ b/Build/build.bat
@@ -3,7 +3,7 @@ set startingDir="%CD%"
set basepath="%~dp0"
cd %basepath%\..\Source
-set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go
+set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingrust.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go
set GOOS=windows
set GOARCH=amd64
diff --git a/Build/build.sh b/Build/build.sh
index 6a9b3065..9510e7fd 100755
--- a/Build/build.sh
+++ b/Build/build.sh
@@ -6,7 +6,7 @@ startingpath="$(pwd)"
basepath="$(cd "$(dirname "$0")" && pwd)"
cd "$basepath/../Source"
-Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go"
+Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingrust.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go"
echo "Build act.win64.exe"
export GOARCH="amd64"
diff --git a/Documentation/Rust.md b/Documentation/Rust.md
new file mode 100644
index 00000000..26bd67d0
--- /dev/null
+++ b/Documentation/Rust.md
@@ -0,0 +1,123 @@
+# Rust bindings
+
+ACT generates a Rust crate that loads a component at run time (`dlopen`/`LoadLibrary`), like the other dynamic bindings. Rust is a binding language only; ACT does not generate implementation stubs in Rust.
+
+## Generating
+
+Add a binding to the component description:
+
+```xml
+
+
+
+```
+
+ACT writes `Bindings/Rust/Cargo.toml` and `Bindings/Rust/src/lib.rs`. The crate has no dependencies besides other generated crates of imported components. Add it to your project as a path dependency:
+
+```toml
+[dependencies]
+libprimes = { path = "LibPrimes_component/Bindings/Rust" }
+```
+
+Unless ACT is called with `-suppressexamples`, ACT also writes a small application to `Examples/Rust`.
+
+## Requirements
+
+Rust 1.65 or newer. Older compilers down to 1.57 build the crates but warn about nested `unsafe` blocks.
+
+## Using a component
+
+```rust
+use libprimes::Wrapper;
+
+fn main() -> libprimes::Result<()> {
+ let wrapper = Wrapper::new("path/to/libprimes")?; // the platform's file extension is not added
+ let (major, minor, micro) = wrapper.get_version()?;
+ println!("version {major}.{minor}.{micro}");
+ let calculator = wrapper.create_factorization_calculator()?;
+ calculator.set_value(735)?;
+ calculator.calculate()?;
+ for factor in calculator.get_prime_factors()? {
+ let (prime, multiplicity) = (factor.prime, factor.multiplicity);
+ println!("{prime}^{multiplicity}");
+ }
+ Ok(())
+}
+```
+
+* Function names are snake case (`GetPrimeFactors` becomes `get_prime_factors`). Names that are keywords in Rust get a trailing underscore.
+* `return` and `out` parameters are returned: a single value as is, several as a tuple. Every call returns `Result`.
+* Instances are released when they are dropped. They keep the library loaded for as long as any of them is alive.
+* Strings are `&str` in and `String` out; arrays are slices in and `Vec` out.
+
+### Errors
+
+`Error` has the public fields `code` and `message`. Its `Display` output reads `Error NAME (code): message`. The codes are available as constants in the `error_code` module.
+
+### Types
+
+| IDL | Rust |
+| --- | --- |
+| `uint8`...`int64`, `single`, `double`, `bool` | `u8`...`i64`, `f32`, `f64`, `bool` |
+| `pointer` | `*mut c_void` |
+| `enum` | a Rust `enum` with explicit values |
+| `struct` | `#[repr(C)]` struct, or `#[repr(C, packed)]` where C would add padding |
+| `rows`/`columns` members | `[T; rows]` or `[[T; rows]; columns]`, indexed `[column][row]` like the other bindings |
+
+Structs of the C ABI are packed without padding. A packed struct cannot be borrowed field by field: copy the field into a local first, as in the example above.
+
+Enumerations written by the library are checked before they reach your code. A value that the binding does not know yields an error with the code for an invalid cast.
+
+## Classes
+
+Classes are structs that dereference to their parent class, so the methods of the parent are available on the child. Every class implements `Class`, which carries the type identifiers used for run-time type checks:
+
+* `instance.is::()` tells whether an instance is, or derives from, a class.
+* `instance.cast::()` returns a new reference as `Option`.
+* `instance.downcast::()` consumes the instance and returns `Result`.
+* `animal.into_kind()` returns an enum with a variant per derived class, to be used in a `match`.
+
+These need a `classtypeidmethod` in the IDL.
+
+## Threads
+
+Instances are `Send`. They are `Sync` only if the class is declared with `threadsafetyoption="strict"`; the library protects such instances for every call. For `soft` and `none`, share an instance between threads only if you serialise the calls yourself.
+
+## Callbacks
+
+A function type with a user data pointer, used by a method that takes the callback and the pointer, is offered with closures:
+
+```rust
+let calls = Arc::new(AtomicUsize::new(0));
+let counter = calls.clone();
+writer.set_progress_callback(move |progress, _identifier| {
+ counter.fetch_add(1, Ordering::SeqCst);
+ progress > 0.5 // the value returned for an `out` or `return` parameter is written back
+})?;
+```
+
+* Parameters of the function type become closure arguments (strings as `&str`, arrays as slices, enumerations checked, classes as borrowed references). `out` and `return` parameters become the return value of the closure, a tuple if there are several.
+* The closure has to be `Send + 'static`. Several callbacks of one method share state through an `Arc>`.
+* The closure is kept until the same callback is set again on the same instance, or until the wrapper is dropped. Do not capture the `Wrapper` or class instances in the closure, as that would create a reference cycle keeping the library loaded.
+* The library may call the closure from any thread. Calls of one callback are serialised, so the closure must not cause the same callback to be called again while it runs. Do not replace a callback while the library may concurrently invoke the previously registered one.
+* A panic in the closure aborts the process, because it cannot unwind through the library.
+
+The same method exists with the callbacks of the C ABI as `_raw`. It is `unsafe` and takes the function pointer and the user data. Function types that cannot be mapped (no user data pointer, arrays or structs that the callback has to fill) are only available this way, under their normal name. Callback functions have to be `unsafe extern "C" fn`, must not panic, and anything they are given has to outlive the registration.
+
+## Injection
+
+If a component imports another one, the binding of the importing component depends on the binding of the imported one. Load both and pass the imported wrapper:
+
+```rust
+let numbers = numbers::Wrapper::new(numbers_path)?;
+let wrapper = calculation::Wrapper::new(calculation_path)?;
+wrapper.inject_numbers(&numbers)?;
+```
+
+`inject_` keeps the imported wrapper alive. The injection function of the IDL (named by `injectionmethod`, `inject_component` in the example) takes the raw symbol lookup method and is `unsafe`.
+
+## Platforms and status
+
+The binding is tested on macOS (arm64) and in the Linux image of the CI, and its Windows code path is checked with `cargo check --target x86_64-pc-windows-gnu`. Generated crates build without warnings with `cargo clippy`.
+
+The `enumarray` parameter type is accepted by the IDL but no binding of ACT generates it, so the Rust binding does not either.
diff --git a/Examples/Calculator/Calculator.xml b/Examples/Calculator/Calculator.xml
index 28f4485d..e370c72c 100644
--- a/Examples/Calculator/Calculator.xml
+++ b/Examples/Calculator/Calculator.xml
@@ -10,6 +10,7 @@
+
diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml
new file mode 100644
index 00000000..1bd4b391
--- /dev/null
+++ b/Examples/Calculator/Calculator_component/Bindings/Rust/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "calculator"
+version = "1.0.0"
+edition = "2021"
+rust-version = "1.65"
+description = "Rust bindings of Calculator library"
diff --git a/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs
new file mode 100644
index 00000000..8cc7bb19
--- /dev/null
+++ b/Examples/Calculator/Calculator_component/Bindings/Rust/src/lib.rs
@@ -0,0 +1,816 @@
+/*++
+
+Copyright (C) 2019 Calculator developers
+
+All rights reserved.
+
+This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop.
+
+Abstract: This is an autogenerated Rust file in order to allow an easy
+ use of Calculator library
+
+Interface version: 1.0.0
+
+*/
+
+use std::ffi::CString;
+use std::fmt;
+use std::mem;
+use std::os::raw::{c_char, c_void};
+use std::ptr;
+use std::sync::Arc;
+
+#[cfg(unix)]
+mod dynlib {
+ use super::*;
+ use std::ffi::CStr;
+ type DynResult = std::result::Result;
+ #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))]
+ extern "C" {
+ fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
+ fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
+ fn dlclose(handle: *mut c_void) -> i32;
+ fn dlerror() -> *const c_char;
+ }
+ const RTLD_NOW: i32 = 2;
+ pub struct Library {
+ handle: *mut c_void,
+ }
+ impl Library {
+ pub unsafe fn new(path: &str) -> DynResult {
+ let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?;
+ let handle = dlopen(cpath.as_ptr(), RTLD_NOW);
+ if handle.is_null() {
+ return Err(last_error());
+ }
+ Ok(Self { handle })
+ }
+ pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> {
+ let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?;
+ let sym = dlsym(self.handle, csym.as_ptr());
+ if sym.is_null() {
+ return Err(last_error());
+ }
+ Ok(sym)
+ }
+ }
+ impl Drop for Library {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.handle.is_null() {
+ dlclose(self.handle);
+ }
+ }
+ }
+ }
+ fn last_error() -> String {
+ unsafe {
+ let err = dlerror();
+ if err.is_null() {
+ "unknown dlerror".to_string()
+ } else {
+ CStr::from_ptr(err).to_string_lossy().into_owned()
+ }
+ }
+ }
+}
+
+#[cfg(windows)]
+mod dynlib {
+ use super::*;
+ use std::ffi::OsStr;
+ use std::os::windows::ffi::OsStrExt;
+ type DynResult = std::result::Result;
+ type HModule = *mut c_void;
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn LoadLibraryW(lpLibFileName: *const u16) -> HModule;
+ fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void;
+ fn FreeLibrary(hModule: HModule) -> i32;
+ fn GetLastError() -> u32;
+ }
+ pub struct Library {
+ handle: HModule,
+ }
+ impl Library {
+ pub unsafe fn new(path: &str) -> DynResult {
+ if path.contains('\0') {
+ return Err("library path contains NUL".to_string());
+ }
+ let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect();
+ let handle = LoadLibraryW(wide.as_ptr());
+ if handle.is_null() {
+ return Err(last_error());
+ }
+ Ok(Self { handle })
+ }
+ pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> {
+ let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?;
+ let sym = GetProcAddress(self.handle, csym.as_ptr());
+ if sym.is_null() {
+ return Err(last_error());
+ }
+ Ok(sym)
+ }
+ }
+ impl Drop for Library {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.handle.is_null() {
+ FreeLibrary(self.handle);
+ }
+ }
+ }
+ }
+ fn last_error() -> String {
+ let code = unsafe { GetLastError() };
+ format!("Win32 error {}", code)
+ }
+}
+
+use dynlib::Library;
+
+/// Raw handle of an instance living inside of the library.
+pub type Handle = *mut c_void;
+
+/// Converts a buffer filled by the library (including the trailing zero) into a String.
+#[allow(dead_code)]
+fn string_from_buffer(buffer: &[u8], filled: u32) -> String {
+ let length = (filled as usize).saturating_sub(1).min(buffer.len());
+ String::from_utf8_lossy(&buffer[..length]).into_owned()
+}
+
+/// Error codes reported by the library.
+pub mod error_code {
+ pub const SUCCESS: i32 = 0;
+ pub const NOTIMPLEMENTED: i32 = 1;
+ pub const INVALIDPARAM: i32 = 2;
+ pub const INVALIDCAST: i32 = 3;
+ pub const BUFFERTOOSMALL: i32 = 4;
+ pub const GENERICEXCEPTION: i32 = 5;
+ pub const COULDNOTLOADLIBRARY: i32 = 6;
+ pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7;
+ pub const INCOMPATIBLEBINARYVERSION: i32 = 8;
+}
+
+/// Error returned by the Calculator library or by the Rust binding.
+#[derive(Clone, PartialEq, Eq)]
+pub struct Error {
+ pub code: i32,
+ pub message: String,
+}
+
+impl Error {
+ pub fn new(code: i32, message: impl Into) -> Self {
+ Self { code, message: message.into() }
+ }
+
+ /// Name of the error code.
+ pub fn name(&self) -> &'static str {
+ match self.code {
+ error_code::SUCCESS => "SUCCESS",
+ error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED",
+ error_code::INVALIDPARAM => "INVALIDPARAM",
+ error_code::INVALIDCAST => "INVALIDCAST",
+ error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL",
+ error_code::GENERICEXCEPTION => "GENERICEXCEPTION",
+ error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY",
+ error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT",
+ error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION",
+ _ => "UNKNOWN",
+ }
+ }
+
+ /// Generic description of the error code.
+ pub fn description(&self) -> &'static str {
+ match self.code {
+ error_code::SUCCESS => "success",
+ error_code::NOTIMPLEMENTED => "functionality not implemented",
+ error_code::INVALIDPARAM => "an invalid parameter was passed",
+ error_code::INVALIDCAST => "a type cast failed",
+ error_code::BUFFERTOOSMALL => "a provided buffer is too small",
+ error_code::GENERICEXCEPTION => "a generic exception occurred",
+ error_code::COULDNOTLOADLIBRARY => "the library could not be loaded",
+ error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library",
+ error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface",
+ _ => "unknown error",
+ }
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let message = if self.message.is_empty() { self.description() } else { self.message.as_str() };
+ write!(f, "CalculatorError {} ({}): {}", self.name(), self.code, message)
+ }
+}
+
+// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text.
+impl fmt::Debug for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(self, f)
+ }
+}
+
+impl std::error::Error for Error {}
+
+pub type Result = std::result::Result;
+
+/// Table of the functions exported by the library.
+#[allow(non_snake_case)]
+struct Api {
+ calculator_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32,
+ calculator_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32,
+ calculator_releaseinstance: unsafe extern "C" fn(Handle) -> i32,
+ calculator_acquireinstance: unsafe extern "C" fn(Handle) -> i32,
+ calculator_createvariable: unsafe extern "C" fn(f64, *mut Handle) -> i32,
+ calculator_createcalculator: unsafe extern "C" fn(*mut Handle) -> i32,
+ calculator_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32,
+ calculator_variable_getvalue: unsafe extern "C" fn(Handle, *mut f64) -> i32,
+ calculator_variable_setvalue: unsafe extern "C" fn(Handle, f64) -> i32,
+ calculator_calculator_enlistvariable: unsafe extern "C" fn(Handle, Handle) -> i32,
+ calculator_calculator_getenlistedvariable: unsafe extern "C" fn(Handle, u32, *mut Handle) -> i32,
+ calculator_calculator_clearvariables: unsafe extern "C" fn(Handle) -> i32,
+ calculator_calculator_multiply: unsafe extern "C" fn(Handle, *mut Handle) -> i32,
+ calculator_calculator_add: unsafe extern "C" fn(Handle, *mut Handle) -> i32,
+}
+
+impl Api {
+ /// Loads all functions using a function that resolves the address of a symbol by its name.
+ #[allow(clippy::missing_transmute_annotations)]
+ unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result {
+ let load_symbol = |name: &str| -> Result<*mut c_void> {
+ lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e))
+ };
+ Ok(Self {
+ calculator_getversion: mem::transmute(load_symbol("calculator_getversion")?),
+ calculator_getlasterror: mem::transmute(load_symbol("calculator_getlasterror")?),
+ calculator_releaseinstance: mem::transmute(load_symbol("calculator_releaseinstance")?),
+ calculator_acquireinstance: mem::transmute(load_symbol("calculator_acquireinstance")?),
+ calculator_createvariable: mem::transmute(load_symbol("calculator_createvariable")?),
+ calculator_createcalculator: mem::transmute(load_symbol("calculator_createcalculator")?),
+ calculator_base_classtypeid: mem::transmute(load_symbol("calculator_base_classtypeid")?),
+ calculator_variable_getvalue: mem::transmute(load_symbol("calculator_variable_getvalue")?),
+ calculator_variable_setvalue: mem::transmute(load_symbol("calculator_variable_setvalue")?),
+ calculator_calculator_enlistvariable: mem::transmute(load_symbol("calculator_calculator_enlistvariable")?),
+ calculator_calculator_getenlistedvariable: mem::transmute(load_symbol("calculator_calculator_getenlistedvariable")?),
+ calculator_calculator_clearvariables: mem::transmute(load_symbol("calculator_calculator_clearvariables")?),
+ calculator_calculator_multiply: mem::transmute(load_symbol("calculator_calculator_multiply")?),
+ calculator_calculator_add: mem::transmute(load_symbol("calculator_calculator_add")?),
+ })
+ }
+}
+
+/// State shared by the wrapper and all instances created through it, so that the library
+/// stays loaded for as long as any instance is alive.
+struct Inner {
+ api: Api,
+ _lib: Option,
+}
+
+// The function table and the library handle are immutable after loading.
+unsafe impl Send for Inner {}
+unsafe impl Sync for Inner {}
+
+impl Inner {
+ fn new(api: Api, lib: Option) -> Arc {
+ Arc::new(Self {
+ api,
+ _lib: lib,
+ })
+ }
+
+ fn check(&self, handle: Handle, code: i32) -> Result<()> {
+ if code == 0 {
+ return Ok(());
+ }
+ Err(Error::new(code, self.last_error_message(handle)))
+ }
+
+ fn last_error_message(&self, handle: Handle) -> String {
+ if handle.is_null() {
+ return String::new();
+ }
+ let mut needed: u32 = 0;
+ let mut has_error = false;
+ let code = unsafe { (self.api.calculator_getlasterror)(handle, 0, &mut needed, ptr::null_mut(), &mut has_error) };
+ if code != 0 || !has_error || needed == 0 {
+ return String::new();
+ }
+ let mut buffer = vec![0u8; needed as usize];
+ let mut filled: u32 = 0;
+ let code = unsafe { (self.api.calculator_getlasterror)(handle, buffer.len() as u32, &mut filled, buffer.as_mut_ptr() as *mut c_char, &mut has_error) };
+ if code != 0 || !has_error {
+ return String::new();
+ }
+ string_from_buffer(&buffer, filled)
+ }
+}
+
+mod private {
+ pub trait Sealed {}
+}
+
+/// Implemented by all classes of the library. Allows to narrow an instance to a more specific class
+/// with `Base::is` and `downcast`, which Rust cannot do automatically for returned instances.
+pub trait Class: private::Sealed + Sized {
+ #[doc(hidden)]
+ const TYPE_IDS: &'static [u64];
+ #[doc(hidden)]
+ const TYPE_ID: u64;
+ #[doc(hidden)]
+ fn from_base(base: Base) -> Self;
+}
+
+/// Base class of the Calculator library.
+pub struct Base {
+ inner: Arc,
+ handle: Handle,
+}
+
+// Instances may be moved between threads. They may only be shared between threads if the class is
+// declared with the strict threadsafetyoption in the ACT class definition.
+unsafe impl Send for Base {}
+
+impl Base {
+ #[allow(dead_code)]
+ fn from_handle(inner: Arc, handle: Handle) -> Self {
+ Self { inner, handle }
+ }
+
+ /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one
+ /// reference of the handle. This is meant for bindings of components that import this component.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ #[doc(hidden)]
+ pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self {
+ Self::from_handle(wrapper.inner.clone(), handle)
+ }
+
+ /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a
+ /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result {
+ let inner = &wrapper.inner;
+ let code = (inner.api.calculator_acquireinstance)(handle);
+ inner.check(handle, code)?;
+ Ok(Self::from_handle(inner.clone(), handle))
+ }
+
+ fn inner_arc(&self) -> &Arc {
+ &self.inner
+ }
+
+ /// Raw handle of the instance inside of the library.
+ pub fn handle(&self) -> Handle {
+ self.handle
+ }
+
+ fn into_base(self) -> Base {
+ self
+ }
+
+ /// Tells whether the instance is of class `T` or of a class derived from it.
+ pub fn is(&self) -> bool {
+ matches!(self.class_type_id(), Ok(id) if T::TYPE_IDS.contains(&id))
+ }
+
+ /// Returns another reference to the instance as class `T`, or `None` if it is not an instance of `T`.
+ /// In contrast to `downcast`, the instance stays usable, so it can be tested against several classes.
+ pub fn cast(&self) -> Option {
+ if !self.is::() {
+ return None;
+ }
+ let code = unsafe { (self.inner.api.calculator_acquireinstance)(self.handle) };
+ if code != 0 {
+ return None;
+ }
+ Some(T::from_base(Base { inner: self.inner.clone(), handle: self.handle }))
+ }
+
+ /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise.
+ pub fn downcast(self) -> std::result::Result {
+ if self.is::() {
+ Ok(T::from_base(self.into_base()))
+ } else {
+ Err(self)
+ }
+ }
+
+ /// Resolves the most specific class of the instance, to be used in a `match`.
+ pub fn into_kind(self) -> BaseKind {
+ let id = match self.class_type_id() {
+ Ok(id) => id,
+ Err(_) => return BaseKind::Other(self),
+ };
+ if id == Variable::TYPE_ID {
+ return BaseKind::Variable(Variable::from_base(self.into_base()));
+ }
+ if id == Calculator::TYPE_ID {
+ return BaseKind::Calculator(Calculator::from_base(self.into_base()));
+ }
+ BaseKind::Other(self)
+ }
+
+ /// Get Class Type Id
+ ///
+ /// # Returns
+ /// * `class_type_id` - Class type as a 64 bits integer
+ pub fn class_type_id(&self) -> Result {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let mut __act_out_class_type_id: u64 = 0;
+ let __act_code = unsafe { (__act_inner.api.calculator_base_classtypeid)(__act_handle, &mut __act_out_class_type_id) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(__act_out_class_type_id)
+ }
+}
+
+/// The most specific class of a `Base`, see `Base::into_kind`.
+pub enum BaseKind {
+ Variable(Variable),
+ Calculator(Calculator),
+ /// The instance is not of a more specific class (or the class is unknown to this binding).
+ Other(Base),
+}
+
+impl fmt::Debug for Base {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Base").field("handle", &self.handle()).finish()
+ }
+}
+
+impl private::Sealed for Base {}
+
+impl Class for Base {
+ const TYPE_IDS: &'static [u64] = &[0xDDEA9DC03BDC9EC4, 0xC228BBEB32E22A34, 0x5FA5D809D8A728B0];
+ const TYPE_ID: u64 = 0xDDEA9DC03BDC9EC4;
+
+ fn from_base(base: Base) -> Self {
+ base
+ }
+}
+
+impl Drop for Base {
+ fn drop(&mut self) {
+ if !self.handle.is_null() {
+ let _ = unsafe { (self.inner.api.calculator_releaseinstance)(self.handle) };
+ }
+ }
+}
+
+/// A variable number
+pub struct Variable {
+ parent: Base,
+}
+
+impl std::ops::Deref for Variable {
+ type Target = Base;
+
+ fn deref(&self) -> &Base {
+ &self.parent
+ }
+}
+
+impl Variable {
+ #[allow(dead_code)]
+ fn from_handle(inner: Arc, handle: Handle) -> Self {
+ Self { parent: Base::from_handle(inner, handle) }
+ }
+
+ /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one
+ /// reference of the handle. This is meant for bindings of components that import this component.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ #[doc(hidden)]
+ pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self {
+ Self::from_handle(wrapper.inner.clone(), handle)
+ }
+
+ /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a
+ /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result {
+ let inner = &wrapper.inner;
+ let code = (inner.api.calculator_acquireinstance)(handle);
+ inner.check(handle, code)?;
+ Ok(Self::from_handle(inner.clone(), handle))
+ }
+
+ fn into_base(self) -> Base {
+ self.parent.into_base()
+ }
+
+ /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise.
+ pub fn downcast(self) -> std::result::Result {
+ if self.is::() {
+ Ok(T::from_base(self.into_base()))
+ } else {
+ Err(self)
+ }
+ }
+
+ /// Returns the current value of this Variable
+ ///
+ /// # Returns
+ /// * `value` - The current value of this Variable
+ pub fn get_value(&self) -> Result {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let mut __act_out_value: f64 = 0.0;
+ let __act_code = unsafe { (__act_inner.api.calculator_variable_getvalue)(__act_handle, &mut __act_out_value) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(__act_out_value)
+ }
+
+ /// Set the numerical value of this Variable
+ ///
+ /// # Arguments
+ /// * `value` - The new value of this Variable
+ pub fn set_value(&self, value: f64) -> Result<()> {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let __act_code = unsafe { (__act_inner.api.calculator_variable_setvalue)(__act_handle, value) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(())
+ }
+}
+
+impl fmt::Debug for Variable {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Variable").field("handle", &self.handle()).finish()
+ }
+}
+
+impl private::Sealed for Variable {}
+
+impl Class for Variable {
+ const TYPE_IDS: &'static [u64] = &[0xC228BBEB32E22A34];
+ const TYPE_ID: u64 = 0xC228BBEB32E22A34;
+
+ fn from_base(base: Base) -> Self {
+ Variable { parent: base }
+ }
+}
+
+/// Sums up or multiplies a list of variables
+pub struct Calculator {
+ parent: Base,
+}
+
+impl std::ops::Deref for Calculator {
+ type Target = Base;
+
+ fn deref(&self) -> &Base {
+ &self.parent
+ }
+}
+
+impl Calculator {
+ #[allow(dead_code)]
+ fn from_handle(inner: Arc, handle: Handle) -> Self {
+ Self { parent: Base::from_handle(inner, handle) }
+ }
+
+ /// Creates an instance from a handle returned by the library behind `wrapper`. The instance takes over one
+ /// reference of the handle. This is meant for bindings of components that import this component.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ #[doc(hidden)]
+ pub unsafe fn from_raw(wrapper: &Wrapper, handle: Handle) -> Self {
+ Self::from_handle(wrapper.inner.clone(), handle)
+ }
+
+ /// Creates an instance from a handle that is only borrowed, for example one that the library passes to a
+ /// callback. A new reference is acquired, so the instance can be dropped without affecting the caller.
+ ///
+ /// # Safety
+ /// The handle has to be a valid handle of this class that belongs to the library behind `wrapper`.
+ pub unsafe fn from_borrowed(wrapper: &Wrapper, handle: Handle) -> Result {
+ let inner = &wrapper.inner;
+ let code = (inner.api.calculator_acquireinstance)(handle);
+ inner.check(handle, code)?;
+ Ok(Self::from_handle(inner.clone(), handle))
+ }
+
+ fn into_base(self) -> Base {
+ self.parent.into_base()
+ }
+
+ /// Narrows the instance to class `T` if it is an instance of it, or returns it unchanged otherwise.
+ pub fn downcast(self) -> std::result::Result {
+ if self.is::() {
+ Ok(T::from_base(self.into_base()))
+ } else {
+ Err(self)
+ }
+ }
+
+ /// Adds a Variable to the list of Variables this calculator works on
+ ///
+ /// # Arguments
+ /// * `variable` - The new variable in this calculator
+ pub fn enlist_variable(&self, variable: &Variable) -> Result<()> {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let __act_code = unsafe { (__act_inner.api.calculator_calculator_enlistvariable)(__act_handle, variable.handle()) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(())
+ }
+
+ /// Returns an instance of a enlisted variable
+ ///
+ /// # Arguments
+ /// * `index` - The index of the variable to query
+ ///
+ /// # Returns
+ /// * `variable` - The Index-th variable in this calculator
+ pub fn get_enlisted_variable(&self, index: u32) -> Result {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let mut __act_out_variable: Handle = ptr::null_mut();
+ let __act_code = unsafe { (__act_inner.api.calculator_calculator_getenlistedvariable)(__act_handle, index, &mut __act_out_variable) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(Variable::from_handle(__act_inner.clone(), __act_out_variable))
+ }
+
+ /// Clears all variables in enlisted in this calculator
+ pub fn clear_variables(&self) -> Result<()> {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let __act_code = unsafe { (__act_inner.api.calculator_calculator_clearvariables)(__act_handle) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(())
+ }
+
+ /// Multiplies all enlisted variables
+ ///
+ /// # Returns
+ /// * `instance` - Variable that holds the product of all enlisted Variables
+ pub fn multiply(&self) -> Result {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let mut __act_out_instance: Handle = ptr::null_mut();
+ let __act_code = unsafe { (__act_inner.api.calculator_calculator_multiply)(__act_handle, &mut __act_out_instance) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance))
+ }
+
+ /// Sums all enlisted variables
+ ///
+ /// # Returns
+ /// * `instance` - Variable that holds the sum of all enlisted Variables
+ #[allow(clippy::should_implement_trait)]
+ pub fn add(&self) -> Result {
+ let __act_inner = self.inner_arc();
+ let __act_handle = self.handle();
+ let mut __act_out_instance: Handle = ptr::null_mut();
+ let __act_code = unsafe { (__act_inner.api.calculator_calculator_add)(__act_handle, &mut __act_out_instance) };
+ __act_inner.check(__act_handle, __act_code)?;
+ Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance))
+ }
+}
+
+impl fmt::Debug for Calculator {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("Calculator").field("handle", &self.handle()).finish()
+ }
+}
+
+impl private::Sealed for Calculator {}
+
+impl Class for Calculator {
+ const TYPE_IDS: &'static [u64] = &[0x5FA5D809D8A728B0];
+ const TYPE_ID: u64 = 0x5FA5D809D8A728B0;
+
+ fn from_base(base: Base) -> Self {
+ Calculator { parent: base }
+ }
+}
+
+/// Entry point to the Calculator library. Loads the shared library and gives access to its global functions.
+#[derive(Clone)]
+pub struct Wrapper {
+ inner: Arc,
+}
+
+impl Wrapper {
+ /// Loads the library from the given path.
+ pub fn new(library_path: &str) -> Result {
+ let lib = unsafe { Library::new(library_path) }
+ .map_err(|e| Error::new(error_code::COULDNOTLOADLIBRARY, e))?;
+ let api = unsafe { Api::load(|name| lib.get(name)) }?;
+ let wrapper = Self { inner: Inner::new(api, Some(lib)) };
+ wrapper.check_binary_version()?;
+ Ok(wrapper)
+ }
+
+ /// Checks that the loaded library is compatible with the version this binding was generated for.
+ #[allow(clippy::absurd_extreme_comparisons)]
+ fn check_binary_version(&self) -> Result<()> {
+ const BINDING_VERSION_MAJOR: u32 = 1;
+ const BINDING_VERSION_MINOR: u32 = 0;
+ let (major, minor, _micro) = self.get_version()?;
+ if major != BINDING_VERSION_MAJOR || minor < BINDING_VERSION_MINOR {
+ return Err(Error::new(error_code::INCOMPATIBLEBINARYVERSION, "the loaded library is not compatible with this binding"));
+ }
+ Ok(())
+ }
+
+ /// retrieves the binary version of this library.
+ ///
+ /// # Returns
+ /// * `major` - returns the major version of this library
+ /// * `minor` - returns the minor version of this library
+ /// * `micro` - returns the micro version of this library
+ pub fn get_version(&self) -> Result<(u32, u32, u32)> {
+ let __act_inner = &self.inner;
+ let mut __act_out_major: u32 = 0;
+ let mut __act_out_minor: u32 = 0;
+ let mut __act_out_micro: u32 = 0;
+ let __act_code = unsafe { (__act_inner.api.calculator_getversion)(&mut __act_out_major, &mut __act_out_minor, &mut __act_out_micro) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok((__act_out_major, __act_out_minor, __act_out_micro))
+ }
+
+ /// Returns the last error recorded on this object
+ ///
+ /// # Arguments
+ /// * `instance` - Instance Handle
+ ///
+ /// # Returns
+ /// * `error_message` - Message of the last error
+ /// * `has_error` - Is there a last error to query
+ pub fn get_last_error(&self, instance: &Base) -> Result<(String, bool)> {
+ let __act_inner = &self.inner;
+ let mut __act_needed_error_message: u32 = 0;
+ let mut __act_filled_error_message: u32 = 0;
+ let mut __act_buffer_error_message: Vec = Vec::new();
+ let mut __act_out_has_error: bool = false;
+ let __act_code = unsafe { (__act_inner.api.calculator_getlasterror)(instance.handle(), 0, &mut __act_needed_error_message, ptr::null_mut(), &mut __act_out_has_error) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ __act_buffer_error_message.resize(__act_needed_error_message as usize, 0);
+ let __act_code = unsafe { (__act_inner.api.calculator_getlasterror)(instance.handle(), __act_buffer_error_message.len() as u32, &mut __act_filled_error_message, __act_buffer_error_message.as_mut_ptr() as *mut c_char, &mut __act_out_has_error) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok((string_from_buffer(&__act_buffer_error_message, __act_filled_error_message), __act_out_has_error))
+ }
+
+ /// Releases shared ownership of an Instance
+ ///
+ /// # Arguments
+ /// * `instance` - Instance Handle
+ ///
+ /// # Safety
+ /// Decrements the reference count of an instance that is still owned by Rust and will be released again on drop. Only call this if a matching extra reference was previously acquired.
+ pub unsafe fn release_instance(&self, instance: &Base) -> Result<()> {
+ let __act_inner = &self.inner;
+ let __act_code = unsafe { (__act_inner.api.calculator_releaseinstance)(instance.handle()) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok(())
+ }
+
+ /// Acquires shared ownership of an Instance
+ ///
+ /// # Arguments
+ /// * `instance` - Instance Handle
+ pub fn acquire_instance(&self, instance: &Base) -> Result<()> {
+ let __act_inner = &self.inner;
+ let __act_code = unsafe { (__act_inner.api.calculator_acquireinstance)(instance.handle()) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok(())
+ }
+
+ /// Creates a new Variable instance
+ ///
+ /// # Arguments
+ /// * `initial_value` - Initial value of the new Variable
+ ///
+ /// # Returns
+ /// * `instance` - New Variable instance
+ pub fn create_variable(&self, initial_value: f64) -> Result {
+ let __act_inner = &self.inner;
+ let mut __act_out_instance: Handle = ptr::null_mut();
+ let __act_code = unsafe { (__act_inner.api.calculator_createvariable)(initial_value, &mut __act_out_instance) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok(Variable::from_handle(__act_inner.clone(), __act_out_instance))
+ }
+
+ /// Creates a new Calculator instance
+ ///
+ /// # Returns
+ /// * `instance` - New Calculator instance
+ pub fn create_calculator(&self) -> Result {
+ let __act_inner = &self.inner;
+ let mut __act_out_instance: Handle = ptr::null_mut();
+ let __act_code = unsafe { (__act_inner.api.calculator_createcalculator)(&mut __act_out_instance) };
+ __act_inner.check(ptr::null_mut(), __act_code)?;
+ Ok(Calculator::from_handle(__act_inner.clone(), __act_out_instance))
+ }
+}
diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs
new file mode 100644
index 00000000..6795053e
--- /dev/null
+++ b/Examples/Calculator/Calculator_component/Examples/Rust/Calculator_example.rs
@@ -0,0 +1,31 @@
+/*++
+
+Copyright (C) 2019 Calculator developers
+
+All rights reserved.
+
+Abstract: Rust example that exercises the Rust bindings of Calculator library.
+ It only needs the example library of this component.
+
+Interface version: 1.0.0
+
+*/
+
+use calculator::*;
+fn main() -> Result<()> {
+ let wrapper = Wrapper::new(&std::env::args().nth(1).unwrap())?;
+ let (major, minor, micro) = wrapper.get_version()?;
+ println!("Calculator version: {}.{}.{}", major, minor, micro);
+ let calc = wrapper.create_calculator()?;
+ calc.enlist_variable(&wrapper.create_variable(2.0)?)?;
+ calc.enlist_variable(&wrapper.create_variable(3.0)?)?;
+ let sum = calc.add()?.get_value()?;
+ println!(" sum = {}", sum);
+ assert_eq!(sum, 5.0);
+ println!("Changing the value of the first summand");
+ calc.get_enlisted_variable(0)?.set_value(10.0)?;
+ let new_sum = calc.add()?.get_value()?;
+ println!("newSum = {}", new_sum);
+ assert_eq!(new_sum, 13.0);
+ Ok(())
+}
diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml b/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml
new file mode 100644
index 00000000..26d1aeb2
--- /dev/null
+++ b/Examples/Calculator/Calculator_component/Examples/Rust/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "calculator_example"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+calculator = { path = "../../Bindings/Rust" }
+
+[[bin]]
+name = "calculator_example"
+path = "Calculator_example.rs"
diff --git a/Examples/Calculator/Calculator_component/Examples/Rust/build.sh b/Examples/Calculator/Calculator_component/Examples/Rust/build.sh
new file mode 100755
index 00000000..5fa71717
--- /dev/null
+++ b/Examples/Calculator/Calculator_component/Examples/Rust/build.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+set -euxo pipefail
+
+cd "$(dirname "$0")"
+source ../../../../../Build/build.inc
+
+echo "Build Rust example"
+export CARGO_TARGET_DIR=build
+cargo build
+
+echo "Test C++ library"
+./build/debug/calculator_example $PWD/../../Implementations/Cpp/build/calculator$OSLIBEXT
+
+echo "Test Pascal library"
+./build/debug/calculator_example $PWD/../../Implementations/Pascal/build/calculator$OSLIBEXT
diff --git a/Examples/Calculator/build.sh b/Examples/Calculator/build.sh
index e5f61e7e..2764b0f4 100755
--- a/Examples/Calculator/build.sh
+++ b/Examples/Calculator/build.sh
@@ -39,4 +39,10 @@ if command -v python3 >/dev/null 2>&1; then
else
echo "Skipping Python example (python3 not found)"
fi
+
+if command -v cargo >/dev/null 2>&1; then
+ ./Calculator_component/Examples/Rust/build.sh
+else
+ echo "Skipping Rust example (cargo not found)"
+fi
echo "Build and test are done and successful"
diff --git a/Examples/Injection/Calculation.xml b/Examples/Injection/Calculation.xml
index b75f88b9..df31e7a5 100644
--- a/Examples/Injection/Calculation.xml
+++ b/Examples/Injection/Calculation.xml
@@ -15,6 +15,7 @@
+
diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml
new file mode 100644
index 00000000..5872e8d6
--- /dev/null
+++ b/Examples/Injection/Calculation_component/Bindings/Rust/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "calculation"
+version = "1.0.0"
+edition = "2021"
+rust-version = "1.65"
+description = "Rust bindings of Calculation library"
+
+[dependencies]
+numbers = { path = "../../../Numbers_component/Bindings/Rust" }
diff --git a/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs
new file mode 100644
index 00000000..08d069e7
--- /dev/null
+++ b/Examples/Injection/Calculation_component/Bindings/Rust/src/lib.rs
@@ -0,0 +1,798 @@
+/*++
+
+Copyright (C) 2019 Calculation developers
+
+All rights reserved.
+
+This file has been generated by the Automatic Component Toolkit (ACT) version 1.8.1-develop.
+
+Abstract: This is an autogenerated Rust file in order to allow an easy
+ use of Calculation library
+
+Interface version: 1.0.0
+
+*/
+
+use std::ffi::CString;
+use std::fmt;
+use std::mem;
+use std::os::raw::{c_char, c_void};
+use std::ptr;
+use std::sync::Arc;
+
+#[cfg(unix)]
+mod dynlib {
+ use super::*;
+ use std::ffi::CStr;
+ type DynResult = std::result::Result;
+ #[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))]
+ extern "C" {
+ fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
+ fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
+ fn dlclose(handle: *mut c_void) -> i32;
+ fn dlerror() -> *const c_char;
+ }
+ const RTLD_NOW: i32 = 2;
+ pub struct Library {
+ handle: *mut c_void,
+ }
+ impl Library {
+ pub unsafe fn new(path: &str) -> DynResult {
+ let cpath = CString::new(path).map_err(|_| "library path contains NUL".to_string())?;
+ let handle = dlopen(cpath.as_ptr(), RTLD_NOW);
+ if handle.is_null() {
+ return Err(last_error());
+ }
+ Ok(Self { handle })
+ }
+ pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> {
+ let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?;
+ let sym = dlsym(self.handle, csym.as_ptr());
+ if sym.is_null() {
+ return Err(last_error());
+ }
+ Ok(sym)
+ }
+ }
+ impl Drop for Library {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.handle.is_null() {
+ dlclose(self.handle);
+ }
+ }
+ }
+ }
+ fn last_error() -> String {
+ unsafe {
+ let err = dlerror();
+ if err.is_null() {
+ "unknown dlerror".to_string()
+ } else {
+ CStr::from_ptr(err).to_string_lossy().into_owned()
+ }
+ }
+ }
+}
+
+#[cfg(windows)]
+mod dynlib {
+ use super::*;
+ use std::ffi::OsStr;
+ use std::os::windows::ffi::OsStrExt;
+ type DynResult = std::result::Result;
+ type HModule = *mut c_void;
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn LoadLibraryW(lpLibFileName: *const u16) -> HModule;
+ fn GetProcAddress(hModule: HModule, lpProcName: *const c_char) -> *mut c_void;
+ fn FreeLibrary(hModule: HModule) -> i32;
+ fn GetLastError() -> u32;
+ }
+ pub struct Library {
+ handle: HModule,
+ }
+ impl Library {
+ pub unsafe fn new(path: &str) -> DynResult {
+ if path.contains('\0') {
+ return Err("library path contains NUL".to_string());
+ }
+ let wide: Vec = OsStr::new(path).encode_wide().chain(Some(0)).collect();
+ let handle = LoadLibraryW(wide.as_ptr());
+ if handle.is_null() {
+ return Err(last_error());
+ }
+ Ok(Self { handle })
+ }
+ pub unsafe fn get(&self, symbol: &str) -> DynResult<*mut c_void> {
+ let csym = CString::new(symbol).map_err(|_| "symbol contains NUL".to_string())?;
+ let sym = GetProcAddress(self.handle, csym.as_ptr());
+ if sym.is_null() {
+ return Err(last_error());
+ }
+ Ok(sym)
+ }
+ }
+ impl Drop for Library {
+ fn drop(&mut self) {
+ unsafe {
+ if !self.handle.is_null() {
+ FreeLibrary(self.handle);
+ }
+ }
+ }
+ }
+ fn last_error() -> String {
+ let code = unsafe { GetLastError() };
+ format!("Win32 error {}", code)
+ }
+}
+
+use dynlib::Library;
+
+/// Raw handle of an instance living inside of the library.
+pub type Handle = *mut c_void;
+
+/// Converts a buffer filled by the library (including the trailing zero) into a String.
+#[allow(dead_code)]
+fn string_from_buffer(buffer: &[u8], filled: u32) -> String {
+ let length = (filled as usize).saturating_sub(1).min(buffer.len());
+ String::from_utf8_lossy(&buffer[..length]).into_owned()
+}
+
+use std::sync::Mutex;
+
+/// Error codes reported by the library.
+pub mod error_code {
+ pub const SUCCESS: i32 = 0;
+ pub const NOTIMPLEMENTED: i32 = 1;
+ pub const INVALIDPARAM: i32 = 2;
+ pub const INVALIDCAST: i32 = 3;
+ pub const BUFFERTOOSMALL: i32 = 4;
+ pub const GENERICEXCEPTION: i32 = 5;
+ pub const COULDNOTLOADLIBRARY: i32 = 6;
+ pub const COULDNOTFINDLIBRARYEXPORT: i32 = 7;
+ pub const INCOMPATIBLEBINARYVERSION: i32 = 8;
+}
+
+/// Error returned by the Calculation library or by the Rust binding.
+#[derive(Clone, PartialEq, Eq)]
+pub struct Error {
+ pub code: i32,
+ pub message: String,
+}
+
+impl Error {
+ pub fn new(code: i32, message: impl Into) -> Self {
+ Self { code, message: message.into() }
+ }
+
+ /// Name of the error code.
+ pub fn name(&self) -> &'static str {
+ match self.code {
+ error_code::SUCCESS => "SUCCESS",
+ error_code::NOTIMPLEMENTED => "NOTIMPLEMENTED",
+ error_code::INVALIDPARAM => "INVALIDPARAM",
+ error_code::INVALIDCAST => "INVALIDCAST",
+ error_code::BUFFERTOOSMALL => "BUFFERTOOSMALL",
+ error_code::GENERICEXCEPTION => "GENERICEXCEPTION",
+ error_code::COULDNOTLOADLIBRARY => "COULDNOTLOADLIBRARY",
+ error_code::COULDNOTFINDLIBRARYEXPORT => "COULDNOTFINDLIBRARYEXPORT",
+ error_code::INCOMPATIBLEBINARYVERSION => "INCOMPATIBLEBINARYVERSION",
+ _ => "UNKNOWN",
+ }
+ }
+
+ /// Generic description of the error code.
+ pub fn description(&self) -> &'static str {
+ match self.code {
+ error_code::SUCCESS => "success",
+ error_code::NOTIMPLEMENTED => "functionality not implemented",
+ error_code::INVALIDPARAM => "an invalid parameter was passed",
+ error_code::INVALIDCAST => "a type cast failed",
+ error_code::BUFFERTOOSMALL => "a provided buffer is too small",
+ error_code::GENERICEXCEPTION => "a generic exception occurred",
+ error_code::COULDNOTLOADLIBRARY => "the library could not be loaded",
+ error_code::COULDNOTFINDLIBRARYEXPORT => "a required exported symbol could not be found in the library",
+ error_code::INCOMPATIBLEBINARYVERSION => "the version of the binary interface does not match the bindings interface",
+ _ => "unknown error",
+ }
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let message = if self.message.is_empty() { self.description() } else { self.message.as_str() };
+ write!(f, "CalculationError {} ({}): {}", self.name(), self.code, message)
+ }
+}
+
+// Debug prints the readable message, so that `unwrap()` and `fn main() -> Result<()>` report useful text.
+impl fmt::Debug for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(self, f)
+ }
+}
+
+impl std::error::Error for Error {}
+
+impl From for Error {
+ fn from(e: numbers::Error) -> Self {
+ Error::new(e.code, e.message)
+ }
+}
+
+pub type Result = std::result::Result;
+
+/// Table of the functions exported by the library.
+#[allow(non_snake_case)]
+struct Api {
+ calculation_createcalculator: unsafe extern "C" fn(*mut Handle) -> i32,
+ calculation_getversion: unsafe extern "C" fn(*mut u32, *mut u32, *mut u32) -> i32,
+ calculation_getlasterror: unsafe extern "C" fn(Handle, u32, *mut u32, *mut c_char, *mut bool) -> i32,
+ calculation_releaseinstance: unsafe extern "C" fn(Handle) -> i32,
+ calculation_acquireinstance: unsafe extern "C" fn(Handle) -> i32,
+ calculation_injectcomponent: unsafe extern "C" fn(*const c_char, *mut c_void) -> i32,
+ calculation_getsymbollookupmethod: unsafe extern "C" fn(*mut *mut c_void) -> i32,
+ calculation_base_classtypeid: unsafe extern "C" fn(Handle, *mut u64) -> i32,
+ calculation_calculator_enlistvariable: unsafe extern "C" fn(Handle, Handle) -> i32,
+ calculation_calculator_getenlistedvariable: unsafe extern "C" fn(Handle, u32, *mut Handle) -> i32,
+ calculation_calculator_clearvariables: unsafe extern "C" fn(Handle) -> i32,
+ calculation_calculator_multiply: unsafe extern "C" fn(Handle, *mut Handle) -> i32,
+ calculation_calculator_add: unsafe extern "C" fn(Handle, *mut Handle) -> i32,
+}
+
+impl Api {
+ /// Loads all functions using a function that resolves the address of a symbol by its name.
+ #[allow(clippy::missing_transmute_annotations)]
+ unsafe fn load(lookup: impl Fn(&str) -> std::result::Result<*mut c_void, String>) -> Result {
+ let load_symbol = |name: &str| -> Result<*mut c_void> {
+ lookup(name).map_err(|e| Error::new(error_code::COULDNOTFINDLIBRARYEXPORT, e))
+ };
+ Ok(Self {
+ calculation_createcalculator: mem::transmute(load_symbol("calculation_createcalculator")?),
+ calculation_getversion: mem::transmute(load_symbol("calculation_getversion")?),
+ calculation_getlasterror: mem::transmute(load_symbol("calculation_getlasterror")?),
+ calculation_releaseinstance: mem::transmute(load_symbol("calculation_releaseinstance")?),
+ calculation_acquireinstance: mem::transmute(load_symbol("calculation_acquireinstance")?),
+ calculation_injectcomponent: mem::transmute(load_symbol("calculation_injectcomponent")?),
+ calculation_getsymbollookupmethod: mem::transmute(load_symbol("calculation_getsymbollookupmethod")?),
+ calculation_base_classtypeid: mem::transmute(load_symbol("calculation_base_classtypeid")?),
+ calculation_calculator_enlistvariable: mem::transmute(load_symbol("calculation_calculator_enlistvariable")?),
+ calculation_calculator_getenlistedvariable: mem::transmute(load_symbol("calculation_calculator_getenlistedvariable")?),
+ calculation_calculator_clearvariables: mem::transmute(load_symbol("calculation_calculator_clearvariables")?),
+ calculation_calculator_multiply: mem::transmute(load_symbol("calculation_calculator_multiply")?),
+ calculation_calculator_add: mem::transmute(load_symbol("calculation_calculator_add")?),
+ })
+ }
+}
+
+/// State shared by the wrapper and all instances created through it, so that the library
+/// stays loaded for as long as any instance is alive.
+struct Inner {
+ api: Api,
+ _lib: Option,
+ imported_numbers: Mutex