cpython::py_fn! [] [src]

macro_rules! py_fn {
    ($f: ident) => { ... };
    ($f: ident ( $( $pname:ident : $ptype:ty ),* ) ) => { ... };
}

Creates a Python callable object that invokes a Rust function.

There are two forms of this macro: 1) py_fn!(f) f is the name of a rust function with the signature fn(Python, &PyTuple, Option<&PyDict>) -> PyResult<R> for some R that implements ToPyObject.

2) py_fn!(f(parameter_list)) This form automatically converts the arguments into the Rust types specified in the parameter list, and then calls f(Python, Parameters). See py_argparse!() for details on argument parsing.

The macro returns an unspecified type that implements ToPyObject. The resulting python object is a callable object that invokes the Rust function.

Example

#![feature(plugin)]
#![plugin(interpolate_idents)]
#[macro_use] extern crate cpython;
use cpython::{Python, PyResult, PyErr, PyDict};
use cpython::{exc};

fn multiply(py: Python, lhs: i32, rhs: i32) -> PyResult<i32> {
    match lhs.checked_mul(rhs) {
        Some(val) => Ok(val),
        None => Err(PyErr::new_lazy_init(py.get_type::<exc::OverflowError>(), None))
    }
}

fn main() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let dict = PyDict::new(py);
    dict.set_item(py, "multiply", py_fn!(multiply(lhs: i32, rhs: i32))).unwrap();
    py.run("print(multiply(6, 7))", None, Some(&dict)).unwrap();
}