cpython::py_method!
[−]
[src]
macro_rules! py_method { ($f: ident) => { ... }; ($f: ident ( $( $pname:ident : $ptype:ty ),* ) ) => { ... }; }
Creates a Python instance method descriptor that invokes a Rust function.
There are two forms of this macro:
1) py_method!(f)
f is the name of a rust function with the signature
fn(Python, &SelfType, &PyTuple, Option<&PyDict>) -> PyResult<R>
for some R that implements ToPyObject.
2) py_method!(f(parameter_list))
This form automatically converts the arguments into
the Rust types specified in the parameter list,
and then calls f(Python, &SelfType, Parameters).
See py_argparse!() for details on argument parsing.
Returns an unspecified type that implements typebuilder::TypeMember<SelfType>.
When the member is added to a type, it results in an instance method descriptor.
Example
#![feature(plugin)] #![plugin(interpolate_idents)] #[macro_use] extern crate cpython; use cpython::{Python, PythonObject, PyResult, PyErr, ObjectProtocol, PyRustObject, PyRustTypeBuilder}; use cpython::{exc}; fn mul(py: Python, slf: &PyRustObject<i32>, arg: i32) -> PyResult<i32> { match slf.get(py).checked_mul(arg) { 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 multiplier_type = PyRustTypeBuilder::<i32>::new(py, "Multiplier") .add("mul", py_method!(mul(arg: i32))) .finish().unwrap(); let obj = multiplier_type.create_instance(py, 3, ()).into_object(); let result = obj.call_method(py, "mul", &(4,), None).unwrap().extract::<i32>(py).unwrap(); assert_eq!(result, 12); }