|
| 1 | +/// Build script to configure linking against the Python library. |
| 2 | +/// |
| 3 | +/// This script is necessary when the crate's code, particularly tests |
| 4 | +/// that interact with the Python interpreter via `pyo3` (e.g., using |
| 5 | +/// `Python::with_gil`, importing modules, calling Python functions), |
| 6 | +/// needs symbols from the Python C API at link time. |
| 7 | +/// |
| 8 | +/// It uses `pyo3-build-config` to detect the Python installation and |
| 9 | +/// prints the required `cargo:rustc-link-search` and `cargo:rustc-link-lib` |
| 10 | +/// directives to Cargo, enabling the linker to find and link against the |
| 11 | +/// appropriate Python library (e.g., libpythonX.Y.so). |
| 12 | +/// |
| 13 | +/// It also adds an RPATH linker argument on Unix-like systems so the |
| 14 | +/// resulting test executable can find the Python library at runtime. |
| 15 | +/// |
| 16 | +/// Note: Each crate whose test target requires Python linking needs its |
| 17 | +/// own `build.rs` with this logic. |
| 18 | +fn main() { |
| 19 | + println!("cargo:rerun-if-changed=build.rs"); |
| 20 | + |
| 21 | + // Set up #[cfg] flags first (useful for conditional compilation) |
| 22 | + pyo3_build_config::use_pyo3_cfgs(); |
| 23 | + |
| 24 | + // Get the Python interpreter configuration directly |
| 25 | + let config = pyo3_build_config::get(); |
| 26 | + |
| 27 | + // Add the library search path if available |
| 28 | + if let Some(lib_dir) = &config.lib_dir { |
| 29 | + println!("cargo:rustc-link-search=native={}", lib_dir); |
| 30 | + |
| 31 | + // Add RPATH linker argument for Unix-like systems (Linux, macOS) |
| 32 | + // This helps the test executable find the Python library at runtime. |
| 33 | + #[cfg(not(windows))] |
| 34 | + println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lib_dir); |
| 35 | + } else { |
| 36 | + println!("cargo:warning=Python library directory not found in config."); |
| 37 | + } |
| 38 | + |
| 39 | + // Add the library link directive if available |
| 40 | + if let Some(lib_name) = &config.lib_name { |
| 41 | + println!("cargo:rustc-link-lib=dylib={}", lib_name); |
| 42 | + } else { |
| 43 | + println!("cargo:warning=Python library name not found in config."); |
| 44 | + } |
| 45 | +} |
0 commit comments