@@ -385,6 +385,8 @@ def setup_android_env(
385385 # Cargo target linker need to be specified after CC is set
386386 setup_rust_cross_compile (config , android_env )
387387
388+ setup_PYO3_cross_compile (python_dir , android_env )
389+
388390 # Format the environment so it can be pasted into a shell when debugging.
389391 for key , value in sorted (android_env .items ()):
390392 if os .environ .get (key ) != value :
@@ -418,6 +420,20 @@ def setup_rust_cross_compile(
418420 log .warning (f"Unable to configure Rust cross-compilation for architecture { cargo_target } " )
419421
420422
423+ def setup_PYO3_cross_compile (
424+ python_dir : Path ,
425+ env : MutableMapping [str , str ],
426+ ) -> None :
427+ # All Python extension modules must therefore be explicitly linked against libpython3.x.so when building for Android.
428+ # See: https://peps.python.org/pep-0738/#linkage
429+ # For projects using PyO3, this requires setting PYO3_CROSS_LIB_DIR to the directory containing libpython3.x.so.
430+ # See: https://pyo3.rs/v0.27.1/building-and-distribution.html#cross-compiling
431+ if env .get ("PYO3_CROSS_LIB_DIR" ):
432+ log .notice ("Not overriding PYO3_CROSS_LIB_DIR as it has already been set" )
433+ else :
434+ env ["PYO3_CROSS_LIB_DIR" ] = str (python_dir / "prefix" / "lib" )
435+
436+
421437def before_build (state : BuildState ) -> None :
422438 if state .options .before_build :
423439 log .step ("Running before_build..." )
0 commit comments