diff --git a/src/instance.rs b/src/instance.rs index 4dffe67f9b2..6e55501f229 100644 --- a/src/instance.rs +++ b/src/instance.rs @@ -98,7 +98,13 @@ impl<'py> Bound<'py, PyAny> { impl<'py, T> Bound<'py, T> { /// Helper to cast to Bound<'py, PyAny> - pub(crate) fn as_any(&self) -> &Bound<'py, PyAny> { + pub fn as_any(&self) -> &Bound<'py, PyAny> { + // Safety: all Bound have the same memory layout, and all Bound are valid Bound + unsafe { std::mem::transmute(self) } + } + + /// Helper to cast to Bound<'py, PyAny> + pub fn into_any(self) -> Bound<'py, PyAny> { // Safety: all Bound have the same memory layout, and all Bound are valid Bound unsafe { std::mem::transmute(self) } } @@ -1724,6 +1730,24 @@ a = A() }); } + #[test] + fn test_bound_as_any() { + Python::with_gil(|py| { + let obj = PyString::new_bound(py, "hello world"); + let any = obj.as_any(); + assert_eq!(any.as_ptr(), obj.as_ptr()); + }); + } + + #[test] + fn test_bound_into_any() { + Python::with_gil(|py| { + let obj = PyString::new_bound(py, "hello world"); + let any = obj.clone().into_any(); + assert_eq!(any.as_ptr(), obj.as_ptr()); + }); + } + #[cfg(feature = "macros")] mod using_macros { use crate::PyCell;