added example of implementing a basic python module
This commit is contained in:
parent
1129131501
commit
be884bfe7f
40
README.md
40
README.md
|
@ -53,3 +53,43 @@ fn main() {
|
|||
}
|
||||
```
|
||||
|
||||
Example library with python bindings:
|
||||
|
||||
The following two files will build with `cargo build`, and will generate a python-compatible library. (On macOS, you will need to rename the output from \*.dynlib to \*.so)
|
||||
|
||||
**`Cargo.toml`:**
|
||||
```toml
|
||||
[lib]
|
||||
name = "rust2py"
|
||||
crate-type = ["dylib"]
|
||||
|
||||
[dependencies]
|
||||
cpython = { git = "https://github.com/dgrunwald/rust-cpython.git" }
|
||||
```
|
||||
|
||||
**`src/lib.rs`**
|
||||
```rust
|
||||
#[macro_use] extern crate cpython;
|
||||
|
||||
use cpython::{PyResult, Python};
|
||||
|
||||
// add bindings to the generated python module
|
||||
// N.B: names: "rust2py" must be the lib name in Cargo.toml
|
||||
py_module_initializer!(librust2py, initlibrust2py, PyInit_librust2py, |py, m| {
|
||||
try!(m.add(py, "__doc__", "This module is implemented in Rust."));
|
||||
try!(m.add(py, "sum_as_string", py_fn!(py, sum_as_string_py(a: i64, b:i64))));
|
||||
Ok(())
|
||||
});
|
||||
|
||||
// logic implemented as a normal rust function
|
||||
fn sum_as_string(a:i64, b:i64) -> String {
|
||||
format!("{}", a + b).to_string()
|
||||
}
|
||||
|
||||
// rust-cpython aware function. All of our python interface could be
|
||||
// declared in a separate module.
|
||||
fn sum_as_string_py(_: Python, a:i64, b:i64) -> PyResult<String> {
|
||||
let out = sum_as_string(a, b);
|
||||
Ok(out)
|
||||
}
|
||||
```
|
||||
|
|
|
@ -53,7 +53,7 @@ macro_rules! py_method_def {
|
|||
/// 1. `py_fn!(py, f(parameter_list))`
|
||||
/// 1. `py_fn!(py, f(parameter_list) -> PyResult<T> { body })`
|
||||
///
|
||||
/// All three forms return a value of type `PyObject`.
|
||||
/// both forms return a value of type `PyObject`.
|
||||
/// This python object is a callable object that invokes
|
||||
/// the Rust function when called.
|
||||
///
|
||||
|
|
Loading…
Reference in New Issue