A library crate provides Rust code for inclusion by another executable. It contains lib.rs and cannot run by itself, unlike an executable crate with main.rs. section 6.4
Convert an executable crate into a library crate incrementally:
- Rename main.rs to lib.rs. section 6.4
- Delete the main function. section 6.4
- Add integration glue when another environment, such as Python, will load the library. section 6.4
Rust library used from Python
A rust_json crate defines sum in lib.rs, exposes it with PyO3, and registers it in a Python module. After maturin develop, Python imports rust_json and calls rust_json.sum(...). section 6.4
[package]
name = "rust_json"
version = "0.1.0"
edition = "2018"
[lib] #1
crate-type = ["cdylib"]
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
pyo3 = { version = "0.14", features = ["extension-module"] } #2
The Cargo configuration shows a library target using the cdylib crate type and PyO3's extension-module feature. section 6.4
