Skip to main content

call_function_property/
call_function_property.rs

1// Calling function properties: properties whose value is a callable object.
2//
3// The reference device exposes "Sum" and "SumList" function properties nested
4// under its "Protected" object property.  Reading such a property yields a
5// callable [`opendaq::FunctionObject`] to invoke with boxed arguments.
6
7use opendaq::{Device, FunctionObject, Instance, Value};
8
9/// The value of a FUNC-typed property, as the callable it is.
10fn function_property(device: &Device, name: &str) -> opendaq::Result<FunctionObject> {
11    device
12        .property_value(name)?
13        .into_object()?
14        .cast::<FunctionObject>()
15}
16
17fn main() -> opendaq::Result<()> {
18    let instance = Instance::new()?;
19    let device = instance.add_device("daqref://device0")?.expect("device");
20
21    let sum = function_property(&device, "Protected.Sum")?;
22    println!(
23        "Protected.Sum(7, 5)   = {}",
24        sum.call(&[Value::from(7), Value::from(5)])?
25    );
26    println!(
27        "Protected.Sum(40, 2)  = {}",
28        sum.call(&[Value::from(40), Value::from(2)])?
29    );
30    println!(
31        "Protected.Sum(100, 1) = {}",
32        function_property(&device, "Protected.Sum")?.call(&[Value::from(100), Value::from(1)])?
33    );
34
35    // SumList takes a single argument: a list of numbers.
36    let sum_list = function_property(&device, "Protected.SumList")?;
37    println!(
38        "Protected.SumList([1, 2, 3, 4]) = {}",
39        sum_list.call(&[Value::from(vec![1, 2, 3, 4])])?
40    );
41    println!(
42        "Protected.SumList([]) = {}",
43        sum_list.call(&[Value::List(Vec::new())])?
44    );
45
46    // `call` passes arguments straight through, and an implementation is free
47    // to ignore extras (the reference device's Sum does).  The declared
48    // signature lives in the property's callable info -- check the arity
49    // there before calling when it matters.
50    let info = device
51        .property("Protected.Sum")?
52        .expect("Sum property")
53        .callable_info()?
54        .expect("callable info");
55    let expected = info.arguments()?.len();
56    let args = [Value::from(1), Value::from(2), Value::from(3)];
57    if args.len() == expected {
58        println!("\nProtected.Sum(1, 2, 3) = {}", sum.call(&args)?);
59    } else {
60        println!(
61            "\nWrong arity is rejected: Protected.Sum expects {expected} arguments, got {}.",
62            args.len()
63        );
64    }
65    Ok(())
66}