2017-06-18 02:02:02 +00:00
|
|
|
# Python Function
|
|
|
|
|
2018-04-30 21:17:09 +00:00
|
|
|
Pyo3 supports two ways to define a function in python. Both require registering
|
|
|
|
the function to a [module](./module.md)
|
|
|
|
|
|
|
|
One way is defining the function in the module definition.
|
|
|
|
|
|
|
|
```rust
|
|
|
|
#![feature(proc_macro)]
|
|
|
|
|
|
|
|
extern crate pyo3;
|
2018-07-08 21:33:48 +00:00
|
|
|
use pyo3::prelude::*;
|
|
|
|
use pyo3::pymodinit;
|
2018-04-30 21:17:09 +00:00
|
|
|
|
2018-07-09 22:13:02 +00:00
|
|
|
#[pymodinit]
|
|
|
|
fn rust2py(py: Python, m: &PyModule) -> PyResult<()> {
|
2018-04-30 21:17:09 +00:00
|
|
|
|
|
|
|
// Note that the `#[pyfn()]` annotation automatically converts the arguments from
|
|
|
|
// Python objects to Rust values; and the Rust return value back into a Python object.
|
|
|
|
#[pyfn(m, "sum_as_string")]
|
2018-05-05 13:50:04 +00:00
|
|
|
fn sum_as_string_py(_py: Python, a:i64, b:i64) -> PyResult<String> {
|
2018-04-30 21:17:09 +00:00
|
|
|
Ok(format!("{}", a + b).to_string())
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
# fn main() {}
|
|
|
|
```
|
|
|
|
|
|
|
|
The other is annotating a function with `#[py::function]` and then adding it
|
|
|
|
to the module using the `add_function_to_module!` macro, which takes the module
|
|
|
|
as first parameter, the function name as second and an instance of `Python`
|
|
|
|
as third.
|
|
|
|
|
|
|
|
```rust
|
2018-05-05 13:50:04 +00:00
|
|
|
#![feature(proc_macro, concat_idents)]
|
2018-04-30 21:17:09 +00:00
|
|
|
|
|
|
|
#[macro_use]
|
|
|
|
extern crate pyo3;
|
2018-07-08 21:33:48 +00:00
|
|
|
use pyo3::prelude::*;
|
2018-04-30 21:17:09 +00:00
|
|
|
|
2018-07-08 21:33:48 +00:00
|
|
|
use pyo3::{pyfunction, pymodinit};
|
2018-05-05 13:50:04 +00:00
|
|
|
|
|
|
|
#[pyfunction]
|
2018-04-30 21:17:09 +00:00
|
|
|
fn double(x: usize) -> usize {
|
|
|
|
x * 2
|
|
|
|
}
|
|
|
|
|
2018-07-09 22:13:02 +00:00
|
|
|
#[pymodinit]
|
|
|
|
fn module_with_functions(py: Python, m: &PyModule) -> PyResult<()> {
|
2018-05-05 13:50:04 +00:00
|
|
|
m.add_function(wrap_function!(double)).unwrap();
|
2018-04-30 21:17:09 +00:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
# fn main() {}
|
|
|
|
```
|
|
|
|
|