hold onto module name properly in `PyCFunction::internal_new`

This commit is contained in:
David Hewitt 2023-11-21 11:41:50 +00:00
parent 79a54cfc05
commit 015f028589
1 changed files with 9 additions and 6 deletions

View File

@ -4,7 +4,7 @@ use crate::prelude::*;
use crate::{ use crate::{
ffi, ffi,
impl_::pymethods::{self, PyMethodDef}, impl_::pymethods::{self, PyMethodDef},
types::{PyCapsule, PyDict, PyTuple}, types::{PyCapsule, PyDict, PyString, PyTuple},
}; };
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
use std::ffi::CStr; use std::ffi::CStr;
@ -108,12 +108,11 @@ impl PyCFunction {
py_or_module: PyFunctionArguments<'py>, py_or_module: PyFunctionArguments<'py>,
) -> PyResult<&'py Self> { ) -> PyResult<&'py Self> {
let (py, module) = py_or_module.into_py_and_maybe_module(); let (py, module) = py_or_module.into_py_and_maybe_module();
let (mod_ptr, module_name) = if let Some(m) = module { let (mod_ptr, module_name): (_, Option<Py<PyString>>) = if let Some(m) = module {
let mod_ptr = m.as_ptr(); let mod_ptr = m.as_ptr();
let name: Py<PyAny> = m.name()?.into_py(py); (mod_ptr, Some(m.name()?.into_py(py)))
(mod_ptr, name.as_ptr())
} else { } else {
(std::ptr::null_mut(), std::ptr::null_mut()) (std::ptr::null_mut(), None)
}; };
let (def, destructor) = method_def.as_method_def()?; let (def, destructor) = method_def.as_method_def()?;
@ -121,11 +120,15 @@ impl PyCFunction {
let def = Box::into_raw(Box::new(def)); let def = Box::into_raw(Box::new(def));
std::mem::forget(destructor); std::mem::forget(destructor);
let module_name_ptr = module_name
.as_ref()
.map_or(std::ptr::null_mut(), Py::as_ptr);
unsafe { unsafe {
py.from_owned_ptr_or_err::<PyCFunction>(ffi::PyCFunction_NewEx( py.from_owned_ptr_or_err::<PyCFunction>(ffi::PyCFunction_NewEx(
def, def,
mod_ptr, mod_ptr,
module_name, module_name_ptr,
)) ))
} }
} }